JAVA中的装饰模式浅谈

说起装饰模式,大家能联想到的应该是java中IO哪块的逻辑。下面给大家说说,我理解的装饰模式!

装饰模式由以下4个部分组成:

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

2.具体构建角色:定义一个附加责任的类。例(FileInputStream,FileOutputStream).

3.装饰角色:持有一个构建对象的引用,并定义一个与抽象构件接口一致的接口。例(FilterInputStream,FilterOutputStream).

4.具体装饰角色:负责给构件对象添上附加的责任。例(DataInputStream,DataOutputStram.BufferedInputStream,BufferedOutputStram).

 

 

下面给大家演示一下简单的代码:

(1).抽象构建角色

public interface Component {
	public void doSomething();//抽象构建角色

}


(2).具体构建角色

public class Decorator implements Component {
	
	private Component component;//装饰角色
	
	public Decorator(Component component){
		this.component = component;
	}

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		component.doSomething();	

	}

}


3.装饰角色

public class ConcreteComponent implements Component {

	@Override
	public void doSomething() {//具体构建角色
		// TODO Auto-generated method stub
		System.out.println("功能A");

	}

}


(4).具体装饰角色A

public class ConcreteDecorator1 extends Decorator {
	public ConcreteDecorator1(Component component){//具体装饰角色
		super(component);
	}
	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		super.doSomething();
		this.doAnthorthing();
		
	}
	private void doAnthorthing(){
		System.out.println("功能B");
		
	}

}

(5).具体装饰角色B

public class ConcreteDecorator2 extends Decorator {
	
	public ConcreteDecorator2(Component component){//具体装饰角色
		super(component);
	}
	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		super.doSomething();
		this.doAnthorthing();
	}
	private void doAnthorthing(){
		System.out.println("功能C");
	}

}


 

测试类

public class ComponentTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//节点流
		Component component = new ConcreteComponent();
		//过滤流
		Component component1 = new ConcreteDecorator1(component);
		//过滤流
		Component component2 = new ConcreteDecorator2(component1);
		
		component2.doSomething();
		

	}

}


 

大家可以参考下!!

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值