设计模式之装饰模式

  1. 通过穿衣打扮案例来简单梳理策略模式
    1. 装饰模式实现
      1. 定义基类
      2. 定义具体服饰类
      3. 定义业务方法
      4. 运行结果
      5. 结果分析
  2. 联系作者
    1. 微信公众号
    2. QQ群

通过穿衣打扮案例来简单梳理策略模式

每天穿衣打扮需要搭配不同的着装,需要穿哪些衣物以及先穿什么,后穿什么。
这里就涉及到一种设计模式,装饰模式。

装饰模式实现

定义基类

Person代表穿衣服的人

//具体Person类
public class Person {

    public Person(){

    }
    private String name;

    public Person(String name){
        this.name = name;
    }

    public void Show(){
        System.out.println("装扮的" + name);
    }

}

Finery代表服饰基类,继承自Person

//服饰基类
public class Finery extends Person{
    protected Person component;

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

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

定义具体服饰类

实现几种具体的服饰类,继承自服饰基类

public class BigTrouser extends Finery{
    @Override
    public void Show(){
        System.out.println("垮裤");
        super.Show();
    }
}
public class LeatherShoes extends Finery{
    @Override
    public void Show(){
        System.out.println("皮鞋");
        super.Show();
    }
}
public class Sneakers extends Finery{
    @Override
    public void Show(){
        System.out.println("破球鞋");
        super.Show();
    }
}
public class Suit extends Finery{
    @Override
    public void Show(){
        System.out.println("西装");
        super.Show();
    }
}
public class Tie extends Finery{
    @Override
    public void Show(){
        System.out.println("领带");
        super.Show();
    }
}
public class TShirts extends Finery{
    @Override
    public void Show(){
        System.out.println("大T桖");
        super.Show();
    }
}

定义业务方法

具体业务方法中的使用

public class Decorator {
    public static void func1(){
        Person xm = new Person("小明");

        System.out.println("第一种装扮:");
        Sneakers pqx = new Sneakers();
        BigTrouser kk = new BigTrouser();
        TShirts dtx = new TShirts();

        pqx.Decorate(xm);
        kk.Decorate(pqx);
        dtx.Decorate(kk);
        dtx.Show();

        System.out.println("第二种装扮:");
        LeatherShoes px = new LeatherShoes();
        Tie ld = new Tie();
        Suit xz = new Suit();

        px.Decorate(xm);
        ld.Decorate(px);
        xz.Decorate(ld);
        xz.Show();

    }

    public static void main(String[] args) {
        //装饰模式
        func1();
    }
}

运行结果

第一种装扮:
大T桖
垮裤
破球鞋
装扮的小明
第二种装扮:
西装
领带
皮鞋
装扮的小明

结果分析

从代码中可以看出,装饰模式,是动态的给一个对象添加一些额外的职责,  
就增加功能来说,装饰模式比生成子类更为灵活。  

装饰模式的优点总结下来就是,把类中的装饰功能,从类中搬移出去,简化原有的类。  
这样做更大的好处就是有效的把类的核心职责和装饰功能剥离开,祛除相关类中重复的装饰逻辑。

联系作者

微信公众号

xiaomingxiaola
(BossLiu)

QQ群

58726094


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 384276224@qq.com

×

喜欢就点赞,疼爱就打赏

日记本 网文世界