设计模式-装饰模式

设计模式-装饰模式

装饰模式基本实现

Component

abstract class Component
{
    public abstract void Operation();
}

ConcreteComponent

class ConcreteComponent:Component{
    public override void Operation(){
        Console.WriteLine("具体对象的操作")
    }
}

Decorator

abstract class Decorator:Component
{
    protected Component component;
    public void SetComponent(Component component){
        this.component = component;
    }
    public override void Operation(){
        if(component != null){
            component.Operation();
        }
    }    
}

ConcreteDecorator相关类

class ConcreteDecoratorA:Decrator
{
    private string addedState;
    public override void Operation(){
        base.Operation();
        addedState = "New State";
        Console.WriteLine("具体装饰对象A的操作")}
}

class ConcreteDecoratorB:Decrator
{
    private string addedState;
    public override void Operation(){
        base.Operation();
        AddedBehavior();
        Console.WriteLine("具体装饰对象B的操作")}
    public void AddedBehavior(){
        
    }
}

客户端代码

static void Main(string[] args){
    ConcreteComponent c = new ConcreteComponent();
    ConcreteDecoratorA d1 = new ConcreteDecoratorA();
    ConcreteDecoratorB d2 = new ConcreteDecoratorB();
    d1.SetComponent(c);
    d2.SetComponent(d1);
    d2.Operation();
}

装饰模式实现换装程序

“Person”类 (ConcreteComponent)

class Person{
    public Person(){}
    private string name;
    public Person(string name){
        this.name = name;
    }
    public virtual void show(){
        Console.WriteLine("装扮的{0}",name);
    }
}

服饰类(Decorator)

class Finery:Person
{
    protected Person component;
    //打扮
    public void Decorate(Person component){
        this.component = component;
    }
    public override void Show(){
        if(component != null){
            component.Show();
        }
    }
}

具体服饰类(ConcreteDecorator)

class TShirts:Finery
{
    public override void Show(){
        Console.Write("大T恤");
        base.show();//调用父类的方法            
    }
}

class BigTrouser:Finery
{
    public override void Show(){
        Console.Write("垮裤");
        base.show();//调用父类的方法            
    }
}
// ...

客户端代码

static void Main(string[] args){
    Person xc = new Person("小菜")Console.WriteLine("\n 第一种装扮:");
    Sneakers pqx = new Sneakers();
    BigTrouser kk =new BigTrouser();
    TShirts dtx = new TShirts();
    pqx.Decorate(xc);
    kk.Decorate(pqx);
    dtx.Decorate(kk);
    dtx.show();
}

总结

装饰模式是为已有功能动态地添加更多功能地一种方式。

使用场景:当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。

优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迟意..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值