Java 23种设计模式之装饰器模式

1. 概念

动态的给一个对象添加一下额外的职责,就增加功能来说,
装饰模式比生成子类更加灵活。

2. 创建Person对象

public class Person {

    private String name;

    public Person(){}

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

3. 创建装饰类对象

public class PersonDecorator extends Person {

    protected Person person;


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

    public void  show(){
        if(person != null){
            person.show();
        }
    }
}   

4. 创建具体装饰类对象

1.
public class Sneakers extends PersonDecorator{


    @Override
    public void show() {
        System.out.print("破球鞋 ");
        super.show();
    }
}

2.
public class Suit extends PersonDecorator{

    @Override
    public void show() {
        System.out.print("西装 ");
        super.show();
    }
}

3.
public class Tie extends PersonDecorator{

    @Override
    public void show() {
        System.out.print("领带 ");
        super.show();
    }

}

4.
public class LeatherShoes extends PersonDecorator{

    @Override
    public void show() {
        System.out.print("皮鞋");
        super.show();
    }
}
等等.....

5. 测试类

@org.junit.Test
public void test(){

    Person p = new Person("zlc");
    System.out.println("第一种装扮 :");
    //球鞋
    Sneakers sneakers = new Sneakers();
    //T恤
    TShirt tShirt = new TShirt();
    //垮裤
    Trouser trouser = new Trouser();

    sneakers.decorate(p);

    trouser.decorate(sneakers);

    tShirt.decorate(trouser);

    tShirt.show();
    System.out.println();


    System.out.println("第二种装扮 :");
    //皮鞋
    LeatherShoes leatherShoes = new LeatherShoes();
    //领带
    Tie tie = new Tie();
    //西装
    Suit suit = new Suit();

    leatherShoes.decorate(p);
    tie.decorate(leatherShoes);
    suit.decorate(tie);

    suit.show();
    System.out.println();
}

6.小结

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

你可能感兴趣的:(开发类)