设计模式5---装饰模式

  问题:人要穿衣服,可以穿鞋子,裤子,领带。。。,顺序可以使随机的。

  也就是包含大量随机的操作,但是我们的结果却需要一个明确的顺序去执行这个方法。

  UML图:

该方法的变种是,可以Decorate直接继承自RealComponent。

上图的方法可以通过接口来操作,符合开闭原则。

这样所有实现component接口的类都可以使用Decorate类处理。

 已穿衣服为例:

component接口:

public interface IComponent {
    void show();
}

具体实现类:

public class Person implements IComponent {
    
    private String name;
    
    public Person(String name)
    {
        this.name = name;
    }
    @Override
    public void show() {
        System.out.println("穿衣服的"+name);
    }

}

装饰抽象类:

public abstract class Chothes implements IComponent {
    protected IComponent _mComponent = null;
    
    public void show()
    {
        if(_mComponent!=null)
        {
            _mComponent.show();
        }
    }
    
    public void decorate(IComponent comp)
    {
        _mComponent = comp;
    }
}

通过decorate方法,可以把其他Chothes 的子类传入。

Chothes装饰功能类:

public class Westernstyleclothes extends Chothes {
    
    @Override
    public void show() {
        // TODO Auto-generated method stub
        System.out.print("西装\t");
        super.show();
    }

}

 

public class Tie extends Chothes {

    /* (non-Javadoc)
     * @see com.jayfulmath.designpattern.decorate.Chothes#show()
     */
    @Override
    public void show() {
        System.out.print("领带\t");
        super.show();
    }
    
}
public class Pants extends Chothes {

    /* (non-Javadoc)
     * @see com.jayfulmath.designpattern.decorate.Chothes#show()
     */
    @Override
    public void show() {
        System.out.print("西裤\t");
        super.show();
    }
    
}
public class LeatherShoes extends Chothes {

    /* (non-Javadoc)
     * @see com.jayfulmath.designpattern.decorate.Chothes#show()
     */
    @Override
    public void show() {
        System.out.print("皮鞋\t");
        super.show();
    }
    
}

main函数:

public class DecorateMain extends BasicExample {

    @Override
    public void startDemo() {
        Person mPerson = new Person("小明");
        
        Westernstyleclothes wl = new Westernstyleclothes();
        Pants pt = new Pants();
        Tie ti = new Tie();
        LeatherShoes ls = new LeatherShoes();
        
        ti.decorate(mPerson);
        ls.decorate(ti);
        pt.decorate(ls);
        wl.decorate(pt);
        
        wl.show();
    }

}

 

如上,可以任意更换顺序,但不需改变其他代码,即可实现穿衣服流程的变化。

 

posted on 2014-11-28 14:29  Joyfulmath  阅读(192)  评论(0编辑  收藏  举报

导航