第6章《装饰模式》

前端之家收集整理的这篇文章主要介绍了第6章《装饰模式》前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

的给一个对象添加一些功能

功能放在单独的类,并让这个类包装它所要修饰的对象。

功能和装饰功能分开;去除相关类中重复的装饰逻辑。

添加的新功能,而这些新功能只是为了对曾经的主类做一些修饰,只在特定情况下才会执行的特殊行为。这些新功能代码当然可以添加到原有的主类里,但是这一方面违背了开放-封闭原则,另一方面,也增加了主类的复杂性。这时,通过使用装饰模式,增加一些新类,从而实现有选择且按顺序的包装对象。

添加职责。

添加一些职责。

功能。

添加职责的功能

/**

  • @Author: cxh

  • @CreateTime: 18/1/2 21:20

  • @ProjectName: JavaBaseTest
    */
    public class Person {
    private String name;
    Person(){}//子类实例化时,默认调用父类的无参数构造器方法.如果没有这个方法,则编译报错.

    Person(String name){
    this.name=name;
    }
    public void operation(){
    System.out.println("this is :"+name);
    }
    }



/**

  • @Author: cxh

  • @CreateTime: 18/1/2 21:22

  • @ProjectName: JavaBaseTest
    */
    public class Decorator extends Person {
    protected Person person;
    Decorator(){}

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

    @Override
    public void operation() {
    if(person!=null)
    person.operation();
    }
    }



/**

  • @Author: cxh
  • @CreateTime: 18/1/2 21:31
  • @ProjectName: JavaBaseTest
    */
    public class TShirts extends Decorator {
    @Override
    public void operation() {
    super.operation();
    //调用自己的方法
    funcSelf();
    }
    private void funcSelf(){
    System.out.println("衬衫");
    }
    }



/**

  • @Author: cxh
  • @CreateTime: 18/1/2 21:35
  • @ProjectName: JavaBaseTest
    */
    public class Pants extends Decorator {
    @Override
    public void operation() {
    super.operation();
    //调用自己的方法
    funcSelf();
    }
    private void funcSelf(){
    System.out.println("西裤");
    }
    }



/**

  • @Author: cxh
  • @CreateTime: 18/1/2 21:36
  • @ProjectName: JavaBaseTest
    */
    public class Shoes extends Decorator {
    @Override
    public void operation() {
    super.operation();
    //调用自己的方法
    funcSelf();
    }
    private void funcSelf(){
    System.out.println("高跟鞋");
    }
    }



/**

  • @Author: cxh

  • @CreateTime: 18/1/2 21:38

  • @ProjectName: JavaBaseTest
    */
    public class Client {
    //测试类
    public static void main(String[] args) {
    Person person=new Person("朱莉");
    TShirts tShirts=new TShirts();
    Pants pants=new Pants();
    Shoes shoes=new Shoes();

     tShirts.decorator(person);
     pants.decorator(tShirts);
     shoes.decorator(pants);
     shoes.operation();

    }
    }

输出



Process finished with exit code 0

猜你在找的设计模式相关文章