3.装饰模式
实现穿衣打扮
0. UML图

1.被装饰的最原始的类
/**
 * @author makex
 * @note 被装饰的最根上的类
 * @create 2017-06-13
 */
public class Person {
    public Person() {
    }
    private String name;
    public Person(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("待装饰的"+name);
    }
}
2.装饰父类
* @author makex
 * @note 装饰人的服饰类
 * @create 2017-06-13
 */
public class Finery extends Person{
    protected Person component;
    public void decorator(Person component){
        this.component = component;
    }
    @Override
    public void show() {
        if(component != null)
            component.show();
    }
}
3.具体装饰子类
/**
 * @author makex
 * @note 具体服饰类
 * @create 2017-06-13
 */
public class BigTrouser extends Finery {
    @Override
    public void show() {
        System.out.println("穿跨裤");
        super.show();
    }
}
/**
 * @author makex
 * @note 具体服饰类
 * @create 2017-06-13
 */
public class Suit extends Finery {
    @Override
    public void show() {
        System.out.println("穿西装");
        super.show();
    }
}
/**
 * @author makex
 * @note 具体服饰类
 * @create 2017-06-13
 */
public class Tie extends Finery {
    @Override
    public void show() {
        System.out.println("打领带");
        super.show();
    }
}
4.测试类
/**
 * @author makex
 * @note 测试类
 * @create 2017-06-13
 */
public class TestClass {
    public static void main(String[] args) {
        Person base = new Person("mark");
        System.out.println("第一种装饰");
        BigTrouser bigTrouser = new BigTrouser();
        Suit suit = new Suit();
        Tie tie = new Tie();
        tie.decorator(base);
        suit.decorator(tie);
        bigTrouser.decorator(suit);
        bigTrouser.show();
        /**
         * 第一种装饰
         * 穿跨裤
         * 穿西装
         * 打领带
         * 待装饰的mark
         */
    }
}
    http://www.cnblogs.com/makexu/

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号