400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

Java装饰者模式是什么意思

这篇文章主要讲解了“Java装饰者模式是什么意思”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java装饰者模式是什么意思”吧!

创新互联公司专注于昆明企业网站建设,成都响应式网站建设,商城系统网站开发。昆明网站建设公司,为昆明等地区提供建站服务。全流程按需搭建网站,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

一、定义

装饰模式的设计理念主要是以对客户端透明的方式动态扩展对象的功能,是继承关系的一个替代(继承会产生大量的子类,而且代码有冗余)。装饰模式可以在不创造更多子类的情况下,将对象的功能加以扩展。装饰模式把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展完全是透明的(装饰模式的透明性要求客户端程序不应该将对象声明为具体构件类型或具体装饰类型,而应该全部声明为抽象构件类型),装饰模式的应用在java的I/O流中最为显著。

二、角色
三、Example

以上面所说的动物的例子来写代码演示。

抽象构件角色(对应动物类)

public interface Component {
	void function();
}

具体构件角色(对应狗)

public class ConcreteComponent implements Component {

	@Override
	public void function() {
		System.out.println("基本功能:呼吸+觅食+睡觉");
	}

}

装饰角色

public class Decorator implements Component {

	private Component component; //持有一个Component类型的对象引用
	
	public Decorator(Component component) {
		this.component = component;
	}
	 
	@Override
	public void function() {
		component.function(); //客户端的调用委派给具体的子类
	}

}

具体装饰角色(对应吼叫和吃肉这两个功能)

public class ConcreteDecorator extends Decorator {

	public ConcreteDecorator(Component component) {
		super(component);
	}
	 
	@Override
	public void function() {
		super.function();
		System.out.println("附加功能:");
		this.eat();
		this.bellow();
		
	}
	
	private void eat() {
		System.out.println("吃肉");
	}
	
	private void bellow() {
		System.out.println("吼叫");
	}
}

客户端测试:

public class ClientTest {
	public static void main(String[] args) {
		Component component = new ConcreteComponent(); 
		System.out.println("------装饰前:-------");
		component.function();
		Component newComponent = new ConcreteDecorator(component);
		System.out.println("------装饰后:-------");
		newComponent.function();
	}
}

输出:
------装饰前:-------
基本功能:呼吸+觅食+睡觉
------装饰后:-------
基本功能:呼吸+觅食+睡觉
附加功能:吃肉+吼叫
四、应用

装饰者模式主要应用在Java的I/O流中,如果读者对I/O流体系比较混乱的话,不妨利用装饰者模式去理理思路。OutputStream和InputStream就对应于抽象构件角色(Component),FileInputStream和FileOutputStream就对应具体构件角色(ConcreteComponent),FilterOutputStream和FilterInputStream就对应着装饰角色(Decorator),而BufferedOutputStream,DataOutputStream等等就对应着具体装饰角色。

感谢各位的阅读,以上就是“Java装饰者模式是什么意思”的内容了,经过本文的学习后,相信大家对Java装饰者模式是什么意思这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


本文题目:Java装饰者模式是什么意思
文章起源:http://mzwzsj.com/article/jdghcc.html

其他资讯

让你的专属顾问为你服务