Bridge is a structural design pattern that give you possibility to create undepended hierarchies. Let’s see example.

We have two forms — pdf and html forms and two card types — user card and doc card. If we start to do our task without bridge pattern, we will create pdf and html forms, then for each form we will create cards — PdfUserCard, PdfDocCard, HtmlUserCard and HtmlDocCard. And if we have, for example, 4 form types and 8 doc cards, we receive 32 classes. It’s not good idea. Let’s use bridge pattern to decrease new hierarchy.

We should create interface IForm, classes HtmlForm and PdfForm.

    public interface IForm
    {
        public void PrintUserCard(Card card);
        public void PrintDocCard(Card card);
    }

    public class HtmlForm : IForm
    {
        public void PrintUserCard(Card card)
        {
            Console.WriteLine($"Printing USERCARD HTML: {card.Name} + {card.Content}");
        }
        public void PrintDocCard(Card card)
        {
            Console.WriteLine($"Printing DOCCARD HTML: {card.Name} + {card.Content}");
        }
    }

    public class PdfForm : IForm
    {
        public void PrintUserCard(Card card)
        {
            Console.WriteLine($"Printing USERCARD PDF: {card.Name} + {card.Content}");
        }
        public void PrintDocCard(Card card)
        {
            Console.WriteLine($"Printing DOCCARD PDF: {card.Name} + {card.Content}");
        }
    }

Then we will create Card classes.

    public abstract class Card
    {
        private IForm form;
        public Card(IForm form1)
        {
            this.form = form1;
        }
        public string Name { get; set; }
        public string Content { get; set; }
        public void PrintUserCard()
        {
            form.PrintUserCard(this);
        }
        public void PrintDocCard()
        {
            form.PrintDocCard(this);
        }
    }
    public class UserCard : Card
    {
        public UserCard(IForm form) : base(form)
        {
        }
    }
    public class DocCard : Card
    {
        public DocCard(IForm form) : base(form)
        {
        }
    }

How we can use new classes? Easy! Let’s see. While creating card, we specify concrete form. We do it in constructor.

        static void Main(string[] args)
        {
            IForm htmlForm = new HtmlForm();
            IForm pdfForm = new PdfForm();
            
            UserCard userCard = new UserCard(htmlForm);
            userCard.Name = "Donald McDonald";
            userCard.Content = "Test user content";
            userCard.PrintUserCard();

            DocCard docCard = new DocCard(pdfForm);
            docCard.Name = "First card";
            docCard.Content = "Test card contant";
            docCard.PrintDocCard();

        }