设计模式---装饰模式---3

具体细节看书吧!
在这里插入图片描述
装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰模式是为已有功能动态添加更多功能的一种方式。
优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。

使用时,装饰的顺序很重要,比如加密数据和过滤词汇都可以是数据持久化前的装饰功能,但若先加密了数据再用过滤功能就会出问题。最理想的情况,保证装饰类之间彼此独立。

//Component基类
public class Person
{
    protected Person() { }

    private string name;
    protected Person(string name)
    {
        this.name = name;
    }

    public virtual void Show()
    {
        Debug.Log($"装扮的{name}");
    }
}


//具体的某一派生类
public class XiaoMing : Person
{
    public XiaoMing()
    {

    }

    private string name;
    public XiaoMing(string name)
    {
        this.name = name;
    }

}

//装饰基类
public class Finery : Person
{
    protected Person component;

    public void Decorate(Person component)
    {
        this.component = component;
    }

    public override void Show()
    {
        if (component != null)
        {
            component.Show();
        }
    }
}

//具体装饰派生类
public class TShirts : Finery
{
    public override void Show()
    {
        Debug.Log("大T恤");
        base.Show();
    }
}

//具体装饰派生类
public class BigTrouser : Finery
{
    public override void Show()
    {
        Debug.Log("垮裤!");
        base.Show();
    }
}

使用:

Person person = new XiaoMing("小明");

TShirts shirts = new TShirts();
BigTrouser bigTrouser = new BigTrouser();

shirts.Decorate(person);
bigTrouser.Decorate(shirts);
bigTrouser.Show();

装饰也可在构造函数传入,只需添加相应的构造函数。
类似下面:

//具体装饰派生类
public class TShirts : Finery
{
    public TShirts(Person component) : base(component)
    {
       
    }

    public override void Show()
    {
        Debug.Log("大T恤");
        base.Show();
    }
}

//具体装饰派生类
public class BigTrouser : Finery
{
    public BigTrouser(Person component) : base(component)
    {

    }

    public override void Show()
    {
        Debug.Log("垮裤!");
        base.Show();
    }
}
Person person = new XiaoMing("小明");

TShirts shirts = new TShirts(person);
BigTrouser bigTrouser = new BigTrouser(shirts);
//或者这样:从右往左装饰
//BigTrouser bigTrouser = new BigTrouser(new TShirts(person));

bigTrouser.Show();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值