设计模式-2.装饰模式

装饰模式又称为包装者模式,通过组成包装实现增加所要的功能。通过装饰模式可以在不创造更多子类的情况下将对象的功能加以扩展。

装饰模式的角色分配如下:

抽象构建角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。

具体构建角色(Concrete Component):定义一个即将要接收附加责任的类。

装饰角色(Decoretor):持有一个构建(Compent)对象的引用,并定义一个与抽象构建接口一致的接口。

具体装饰角色(Concrete Decorator):负责给构建对象“贴上”附加的责任。

**************************************************************************************************************

装饰模式与继承比较:                                                                         继承:

可以用来扩展特定对象的功能                                                                     用来扩展一类对象的功能 

不需要子类                                                                                                     需要子类

动态                                                                                                                 静态

运行时分配职责                                                                                             编译时分派职责

*************************************************************************************************************

Component:

public interface Component
{
	public void doSomething();
}

ConcreteComponent:

public class ConcreteComponent implements Component
{
	public void doSomething()
	{
		System.out.println("功能A");
	}
}

Decorator:

public class Decorator implements Component
{
	private Component component;
	
	public Decorator(Component component)
	{
		this.component = component;
	}
	
	public void doSomething()
	{
		component.doSomething();
	}
}

ConcreteDecorator1:

public class ConcreteDecorator1 extends Decorator
{
	public ConcreteDecorator1(Component component)
	{
		super(component);
	}
	
	public void doSomething()
	{
		super.doSomething();
		this.doAnotherThing();
	}
	
	public void doAnotherThing()
	{
		System.out.println("功能B");
	}
	
	
}

ConcreteDecorator2:

public class ConcreteDecorator2 extends Decorator
{
	public ConcreteDecorator2(Component component)
	{
		super(component);
	}
	
	public void doSomething()
	{
		super.doSomething();
		this.doAnotherThing();
	}
	
	public void doAnotherThing()
	{
		System.out.println("功能C");
	}
	
	
}

这里定义了两个ConcreteDecorator,类似的根据功能还可以扩展

测试类,Client:

public class Client
{
	public static void main(String[] args)
	{
		Component component = new ConcreteComponent();
		component.doSomething();
		System.out.println("------------------------");
		Component component2 = new ConcreteDecorator1(component);
		component2.doSomething();
		System.out.println("------------------------");
		Component component3 = new ConcreteDecorator2(component2);
		component3.doSomething();
		
	}
}

实验结果:


没经过一次decorator装饰,则会增加相应的功能

实际在IO中也会引用该模式,根据输入输出流的需要,进行一层层嵌套,实现相应的要求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值