装饰模式

概念

  装饰模式是一种向已有的对象添加新功能的结构型模式,他创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

角色

抽象构建:他是具体构建和抽象装饰者的共同父类,用于定义业务方法。
具体构建:实现抽象构建的业务方法。
抽象装饰者类:实现抽象构建,并维护一个指向抽象构件对象的引用,通过该引用可以调用装饰之前构件对象的方法,并通过其子类扩展该方法,以达到装饰的目的。
具体装饰者:继承抽象装饰者,实现扩充方法。

Code

以前端构建界面时的各种View为例。

抽象构建
public interface View {
	
	public void display();
}
具体构建

Button

public class Button implements View{

	@Override
	public void display() {
		System.out.println("show button");		
	}

}

TextView

public class TextView implements View{

	@Override
	public void display() {
		System.out.println("show TextView");
	}

}
抽象装饰者

这里持有一个View子类的引用,用于扩充该View的内容。

public class AbsDecorator implements View{

	private View view;
	
	public AbsDecorator(View view) {
		this.view = view;
	}
	
	@Override
	public void display() {
		view.display();
	}

}
具体装饰者

实现了一个ImageButton

public class ImageDecorator extends AbsDecorator{

	public ImageDecorator(View view) {
		super(view);
	}
	
	@Override
	public void display() {
		super.display();
		showImage();
	}
	
	private void showImage(){
		System.out.println("show image");
	}

}
客户端测试类
public class DecoratorClient {
	public static void main(String[] args) {
		View button = new Button();
		View deco = new ImageDecorator(button);
		deco.display();
	}
}

测试结果

The End

这样就实现了一个简单的装饰者模式了,这样我们想扩展一个类的时候不用非要继承他了。
优点: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点: 多层装饰比较复杂。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值