大话设计模式学习笔记 -- 装饰模式

目录

Person类

装饰抽象类

装饰抽象类具体实现类

客户端代码


 

Person类

public class Person {
    private String name;

    public Person(){

    }

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

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

装饰抽象类

/**
 * 服饰类
 */
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();
    }
}

装饰抽象类具体实现类

/**
 * 具体服饰类--T恤
 */
public class TShirts extends Finery{
    @Override
    public void show() {
        System.out.print("大T恤 ");
        super.show();
    }
}
/**
 * 垮裤
 */
public class BigTrouser extends Finery {
    @Override
    public void show() {
        System.out.print("垮裤 ");
        super.show();
    }
}
/**
 * 破球鞋
 */
public class Sneakers extends Finery {
    @Override
    public void show() {
        System.out.print("破球鞋 ");
        super.show();
    }
}
/**
 * 领带
 */
public class Tie extends Finery {
    @Override
    public void show() {
        System.out.print("领带 ");
        super.show();
    }
}
/**
 * 皮鞋
 */
public class LeatherShoes extends Finery {
    @Override
    public void show() {
        System.out.print("皮鞋 ");
        super.show();
    }
}
/**
 * 西装
 */
public class Suit extends Finery {
    @Override
    public void show() {
        System.out.print("西装 ");
        super.show();
    }
}

客户端代码

/**
 * 客户端代码
 */
public class TestMain {
    public static void main(String[] args) {
        Person xc = new Person("小菜");
        System.out.println("\n 第一种装扮: ");

        Sneakers sneakers = new Sneakers();
        BigTrouser bigTrouser = new BigTrouser();
        TShirts tShirts = new TShirts();

        sneakers.decorate(xc);
        bigTrouser.decorate(sneakers);
        tShirts.decorate(bigTrouser);
        tShirts.show();

        System.out.println("\n 第二种装扮: ");

        LeatherShoes leatherShoes = new LeatherShoes();
        Tie tie = new Tie();
        Suit suit = new Suit();

        leatherShoes.decorate(xc);
        tie.decorate(leatherShoes);
        suit.decorate(tie);
        suit.show();

    }
}

 

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