装饰模式

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

装饰模式的结构图如下:

 

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

场景介绍

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

人即为一个主体,我们现在需要的是给其添加修饰的衣裳(如:西装、衬衫、皮鞋、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恤 打扮的蜗牛

 

转载于:https://www.cnblogs.com/woniu4/p/8359232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值