Как решить, когда я буду использовать паттерн «Мост» и «Декоратор» в моем проекте, и с фактической концептуальной разницей, они оба - PullRequest
0 голосов
/ 29 марта 2020

Привет, я работаю разработчиком программного обеспечения и начинаю понимать схему проектирования. Пожалуйста, дайте мне представление о схеме моста и декоратора. Я уже прошел предыдущий пост по теме topi c, но я не прояснил это, пожалуйста, помогите мне !!.

Ответы [ 3 ]

0 голосов
/ 29 марта 2020
First of all we need to know what is the meaning of Bridge and Decorator pattern??
Bridge: The GOF definition of Bridge pattern is "Decouple an abstraction from its implementation so that the two can vary independently". and this pattern is fall under structural design pattern, why structural because you are changing the structure of our application.
Let's analysis this : Let you implement a business Logic 

Class Business
{
public void Operation()
{
//you business logic here
}
}

Class Client 
{
Business b=new Business();
b.Operation();
}

please consider in the above "Business" class, is for your application structure that you have implemented and with this structure your client is happy.

Now say after One year your client is requesting you to change their business operation structure as well as previous implemented operational structure remain same for some clients. Now what you will do?
Lets see

Class Business
{
public void Operation()
{
//you business logic here
}

public void NewOperation()
{
//you New business logic here
}
}

Class Client 
{
Business b=new Business();
b.NewOperation();
}


Now assume how many changes you need to done for new operation.
Here bridge pattern help a lot;
interface IOperation
{
void operation();
}

public class ConcreteOPeration:Ioperation
{
void operation
{
//you code
}
}

public class NewConcreteOPeration:Ioperation
{
void operation
{
//you new code code
}
}

Public interface OperationBridege
{
void callOperation();
}

Public Class ConcreteBridge:OperationBridege
{
private Ioperation _ioperation;

public ConcreteBridge(Ioperation _operation )
{
this._ioperation=_operation;
}

void callOperation()
{
this._ioperation.operation();
}

}

class client
{
//Ioperation oprtn =New ConcreteOPeration();//NewConcreteOPeration
//if you change to new operation need know change just 
the new concreteOperation class
Ioperation oprtn =New NewConcreteOPeration();

OperationBridege bridege =new ConcreteBridge(oprtn);
bridege.callOperation();
}

Any where you using this operation nothing impacted in your application for structural changes for this pattern fall under structural design pattern.

Now we discuss about Decorator pattern.
Decorator: The GoF definition is "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."
Lets analysis this if you want to add some additional facilities dynamically in your previously implemented  class then GOF suggested at this situation we will must use decorator design pattern.
Let see an example

public interface IComponent
    {
        void Operation();
    }

    public class ConcreteComponent:IComponent
    {
        public void Operation()
        {
            Console.WriteLine("This is the main functionality!!!");
        }
    }


    public class Decoretor:IComponent
    {
        protected IComponent component;
        public void SetComponent(IComponent _component)
        {
            this.component = _component;
        }


        public virtual void Operation()
        {
            component.Operation();  
        }
    }


    public class ConcreteDecoratorA : Decoretor
    {

        public override void Operation()
        {
            base.Operation();
        }
    }

    public class ConcreteDecoratorB : Decoretor
    {

        public override void Operation()
        {
            base.Operation();
            Show();
        }

        public void Show()
        {
            Console.WriteLine("Additional resposiblity attached");
        }
    }


class Program
    {
        static void Main(string[] args)
        {


            IComponent c = ComponentObjCreator.ComponentCreator();

            //Decoretor d = new ConcreteDecoratorA();//In this class have basic //functionalities
            Decoretor d = new ConcreteDecoratorB();//in this class has some additional 
            functionalities
            d.SetComponent(c);
            d.Operation();


}
}

Actually here we decorated our application structure with some new functionalities
and we are implemented in the "ConcreteDecoratorB" class that's why we are called this decorator business pattern.it's also fall under structural design pattern.
0 голосов
/ 02 апреля 2020

Оба они находятся в категории структурные образцы в Gof.

мы используем паттерн моста, когда нам нужны отдельные логики c, когда нам нужно использовать каждый из них. Например, у вас есть программное обеспечение для отправки пользователям нескольких типов уведомлений, таких как SMS, электронная почта и наборы. здесь мы используем шаблон моста .

С другой стороны, когда нам нужно реализовать систему для добавления некоторого определенного поведения c к объекту, мы используем шаблон Decorator. Например, вы решили создать машину IceCream с несколькими вариантами выбора, такими как мед, хлеб, орехи и ... здесь мы используем шаблон Decorator (также известный как Wrapper).

Ниже приведена полезная информация по ссылкам

Шаблон дизайна декоратора

Шаблон моста Bridge Deign

0 голосов
/ 29 марта 2020

Я нашел Кристофера Охрави на YouTube VLogger, который разместил несколько интересных видеороликов о различных шаблонах дизайна, включая Bridge & Decorator.

Он делает это довольно интересно (рассматривает тему) и представляет его в Довольно простой для понимания способ.

Шаблон декоратора:
https://youtu.be/GCraGHx6gso

Шаблон моста:
https://youtu.be/F1YQ7YRjttI

Вы также можете проверить этот сайт: https://www.oodesign.com/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...