大话设计模式java版本 第六章 装饰模式

装饰模式在web开发中尤其常见,在filter中,用的就是装饰模式,在excute前后添加过滤的方法。
package decorator;

public class Person {
    private String name;
    private int age;
    public Person() {
        super();
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    //抽象出来的公共方法
    public void show(){
        System.out.println(name+"__");
    };

}
package decorator;

public class Finery extends Person {
    private Person component;

    //装饰
    public void Decorate(Person component) {
        this.component = component;
    }
    @Override
    public void show() {
        if(component !=null){

            component.show();
        }
    }
}
package decorator;
/* * 服饰类 */
 class TShirts extends Finery{
    @Override
    public void show() {
        System.out.println("大T恤");
        super.show();
    }
}

class BigTrouser extends Finery{
    @Override
    public void show() {
        System.out.println("垮裤");
        super.show();
    }
}

class Sneakers extends Finery{
    @Override
    public void show() {
        System.out.println("球鞋");
        super.show();
    }
}

class Suit extends Finery{
    @Override
    public void show() {
        System.out.println("西装");
        super.show();
    }
}
package decorator;

public class test {
    public static void main(String[] args) {
        Person p1 = new  Person("Tom", 12);
        Sneakers sn = new Sneakers();
        Suit su = new Suit();
        BigTrouser bt = new BigTrouser();
        TShirts ts = new TShirts();

        ts.Decorate(p1);
        bt.Decorate(ts);
        su.Decorate(bt);
        sn.Decorate(su);
        sn.show();

    }
}

你可能感兴趣的:(java,设计模式)