JAVA设计模式(九)设计模式之装饰器设计模式

前言

      本章讲解设计模式中装饰器设计模式的相关知识

方法

1.概念

与桥接模式类似,该模式也是为了解决类爆炸的问题。但是装饰器模式关注于功能的扩展,真实的角色比较稳定。桥接模式的真实角色在多维度之间不断的变化,具有不确定性。

2.装饰器模式的实现思路

1)新建相应工程

其中,Car(车)为基本对象,Feature接口为Car类具有的基本功能,SuperCar类为装饰类。

ACar,AACar,AAACar为三种不同特性的车。

2)代码展示

Car:

package decorator;

/**
 * 真实对象-普通汽车类
 * 更高级的车为ACar、AACar、AAACar以此类推
 * @author jwang
 *
 */
public class Car implements Feature{

	@Override
	public void move() {
		System.out.println("普通车行走");
	}
	
}

Feature:

package decorator;

public interface Feature {
	/**
	 * 车辆行驶方法
	 */
	public void move();
}

SuperCar:

package decorator;
/**
 * 装饰器类,用来扩充基本对象的功能
 * @author jwang
 *
 */
public class SuperCar implements Feature{

	private Feature car;
	
	public SuperCar(Feature car) {
		super();
		this.car = car;
	}

	@Override
	public void move() {
		car.move();
	}

}

其中一种特性车ACar:

package decorator;

public class ACar extends SuperCar {

	public ACar(Feature car) {
		super(car);
	}
	//A类车新特性
	public void A(){
		System.out.println("A类汽车还可以飞");
	}
	@Override
	public void move() {
		super.move();
		A();
	}
}

由此可见,A类车可以通过传递过来的类型任意的扩充自己的功能。

3)编写测试代码测试

Test:

package decorator;

public class Test {

	public static void main(String[] args) {
		//普通车的行走方式
		Car car = new Car();
		car.move();
		System.out.println("-----------------------");
		//普通车加入A类车行走的优势
		ACar aCar = new ACar(car);
		aCar.move();
		System.out.println("-----------------------");
		//普通车加入AA类车行走的优势
		AACar aaCar = new AACar(car);
		aaCar.move();
		System.out.println("-----------------------");
		//普通车加入AA类车行走的优势和AAA类车行走的优势
		AACar aaCar2 = new AACar(new AAACar(car));
		aaCar2.move();
	}
}

程序执行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值