装饰模式

本文借鉴《大话设计模式》,算是对自己学习的总结,也希望分享下所学知识~~

装饰模式(Decorator):
动态地给一个对象添加一些额外的职责。
增加功能比生成子类更为灵活。

case1:给人搭配不同的服饰系统
使用之前学的继承实现,确保符合开闭原则。

public class Person
{
    public string name;
}

//服饰类
public abstract class Finery
{
    public abstract void WearClother();
}
public class TShirts : Finery
{
    public override void WearClother()
    {
        Console.WriteLine("穿上了 TShirt");
    }
}
public class WearSuit : Finery
{
    public override void WearClother()
    {
        Console.WriteLine("穿上了 WearSuit");
    }
}
public class WearTie : Finery
{
    public override void WearClother()
    {
        Console.WriteLine("穿上了 WearTie");
    }
}

//for test
Person person = new Person();

Finery ts = new TShirts();
Finery ws = new WearSuit();
Finery wt = new WearTie();

ts.WearClother();
ws.WearClother();
wt.WearClother();

这样实现有什么问题?
假如有10件衣服,可以搭配成无数种方案,如果使用子类实现可能产生几十上百个子类,不科学。

而装饰模式,就可以把所需的功能按正确的顺序串联起来进行控制。
什么时候使用?
1.出现这种大范围自由组合的情况。
2.为对象新增特性又不想修改原有代码。

装饰模式的重要概念:
Component:对象接口
ConcreteComponent:具体的对象
Decorator:装饰抽象类,继承Component,从外类扩展Component。

好处:
1.对于Component,无需知道Decorator的存在。
2.ConcreteComponent是具体的装饰对象,负责添加职责。
3.每个装饰对象的实现和如何利用这个对象纠纷离开了,每个对象装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。
4.把类中的装饰功能从类中移除,这样可以简化原有的类。

case2:修改之后

//人物就是核心组件
public class Person
{
    public string name;

    public virtual void WearClother()
    {

    }
}

//把衣服抽取共性,成为核心组件的装饰
public abstract class Clothes : Person
{
    protected Person person;

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

    public override void WearClother()
    {
        if (person != null)
        {
            person.WearClother();
        }
    }
}
public class TShirts : Clothes
{
    public override void WearClother()
    {
        //首先运行原Component的功能,再执行本类的功能,相当于对Component的组件进行了装饰。
        base.WearClother();
        Console.WriteLine("穿上了 TShirts");
    }
}
public class WearSuit : Clothes
{
    public override void WearClother()
    {
        //首先运行原Component的功能,再执行本类的功能,相当于对Component的组件进行了装饰。
        base.WearClother();
        Console.WriteLine("穿上了 WearSuit");
    }
}
public class WearTie : Clothes
{
    public override void WearClother()
    {
        //首先运行原Component的功能,再执行本类的功能,相当于对Component的组件进行了装饰。
        base.WearClother();
        Console.WriteLine("穿上了 WearTie");
    }
}

//for test
Person person = new Person();

Clothes ts = new TShirts();
Clothes ws = new WearSuit();
Clothes wt = new WearTie();

ws.Decorate(ts);
wt.Decorate(ws);
wt.WearClother();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值