一、什么是装饰模式
装饰模式又叫包模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。
二、装饰模式的结构
三、代码实现
定义一个接口Car,所有的车都有一般性
package com.sinwao.decorator;
/**
* 车的基本功能
* @author Administrator
*
*/
public interface Car {
public void run();
public void show();
}
定义一个车的装饰工厂,并且实现Car接口
package com.sinwao.decorator;
public abstract class CarDecorator implements Car{
private Car car;
public CarDecorator(Car car) {
this.car = car;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
具有一般性车的实现
package com.sinwao.decorator;
/**
* 跑车
* @author Administrator
*
*/
public class RunCar implements Car{
public void run() {
System.out.println("车跑起来");
}
public void show() {
this.run();
}
}
接下来对车添加新的功能
package com.sinwao.decorator;
public class SwimCarDecorator extends CarDecorator{
public SwimCarDecorator(Car car) {
super(car);
}
public void run() {
}
public void show() {
this.getCar().show();
this.swim();
}
private void swim() {
System.out.println("车加了潜水功能");
}
}
继续扩展车的功能
package com.sinwao.decorator;
public class FlyCarDecorator extends CarDecorator{
public FlyCarDecorator(Car car) {
super(car);
// TODO Auto-generated constructor stub
}
public void run() {
// TODO Auto-generated method stub
}
public void show() {
this.getCar().show();
this.fly();
}
private void fly() {
System.out.println("车加了飞行功能");
}
}
测试代码实现
package com.sinwao.decorator;
public class TestMain {
public static void main(String[] args) {
Car car = new RunCar();
car.show();
System.out.println("=======");
Car swimCar = new SwimCarDecorator(car);
swimCar.show();
System.out.println("=====");
Car flyCar = new FlyCarDecorator(car);
flyCar.show();
System.out.println("===潜水飞行功能的车===");
Car swimFlyCar = new FlyCarDecorator(swimCar);
//在已有的功能上,创造出更多功能的车
swimFlyCar.show();
}
}
结果输出
四、装饰模式的角色和职责
抽象组件角色:一个抽象接口,是被装饰类和装饰类的父接口
具体组件角色:为抽象组件的实现类
抽象装饰角色:包含一个组件的引用,并定义了与抽象组件一致的接口
具体装饰角色:为抽象装饰角色的实现类。负责具体的装饰
五、总结:
在项目实战中经常被用到,因为该模式的出现很好替代了类的继承关系,并且扩展性较好。
所以该设计模式经常被开发者们使用。很多人只知道怎么用,或者觉得别人设计的架构很好,
这就是学习设计模式的重要性。一个好的框架离不开设计模式,多思考,多总结,你也可以设计出很好的框架。