装饰模式

装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。【大话设计模式】

装饰模式的结构图如下:

 

个人认为,装饰即修饰,动态的给主类添加一些功能,而不需要修改主类的功能。

场景介绍

如大话模式一书中提到的穿衣的场景。

人即为一个主体,我们现在需要的是给其添加修饰的衣裳(如:西装、衬衫、皮鞋、T恤、短裤、运动鞋、运动裤、休闲裤等),当然,你也可以什么都不穿(裸奔的场景也是需要的)。

我们不可能在新增加了一种装饰之后,就增加所有可能的子类,这样逐渐会有无线多的类,当客户端去调用类时,比较麻烦,我们的系统也是很庞大,代码的复用性也不好。

通过装饰模式就可以做到动态的修饰人这个主体了。只需要根据自己想法动态调整自己的风格,不用拘束于现有的模式(风格的多样化)

 

代码实现:

主体类Person

public class Person
{
    private String name;
    
    public Person()
    {
    }
  
    public Person(String name)
    {
        this.name = name;
    }
    
    public void show()
    {
        System.out.println("打扮的" + name);
    }
}

 

修饰的服装类

public class Finery extends Person
{
    private Person component;
    
    public Finery(Person component)
    {
        this.component = component;
    }
    
    public void show()
    {
        if(component != null)
        {
            component.show();            
        }

    }
}

其他的装饰类

public class Suit extends Finery
{

    public Suit(Person component)
    {
        super(component);
    }
    
    @Override
    public void show()
    {
        System.out.print("西装 ");
        super.show();
    }
    
}
public class Sneakers extends Finery
{

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

其他的类似,不再一一列举;

客户端调用类

public class Client
{
    public static void main(String[] args)
    {
        Person person = new Person("蜗牛");
        Suit suit = new Suit(person);
        Sneakers sn = new Sneakers(suit);
        Tie tie = new Tie(sn);
        tie.show();
        
        
        TShirts tShirts = new TShirts(person);
        BigTrouser bt = new BigTrouser(tShirts);
        bt.show();
    }
}

结果如下:

领带 皮鞋 西装 打扮的蜗牛
垮裤 T恤 打扮的蜗牛

 

posted @ 2018-01-26 17:05  woniu4  阅读(116)  评论(0编辑  收藏  举报