版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nothingchoice/article/details/88777634
装饰模式(Decorator)的核心作用是动态的为一个对象增加新的的功能。
装饰模式是是一种代替继承的技术,无需通过加成增加子类就可以扩展对象的新功能。使用对象的关联关系代替继承关系可以使程序更加灵活,同时避免类型体系的快速膨胀。
装饰模式在开发中的应用场景如下:
1、I/O中输入输出流的设计。
2、Swing保重图形界面构建功能
3、Struts2中 ,request、response、session对象的处理
4、在Spring中也有大量应用。
package qf;
import java.security.ProtectionDomain;
interface ICar{
void move();
}
//具体构件
class Car implements ICar{
@Override
public void move() {
System.out.println("陆地上跑");
}
}
//装饰角色
class SuperCar implements ICar{
protected ICar icar;
public SuperCar(ICar icar) {
super();
this.icar = icar;
}
@Override
public void move() {
icar.move();
}
}
//具体的装饰角色
class FlyCar extends SuperCar{
public FlyCar(ICar icar) {
super(icar);
}
public void fly() {
System.out.println("在天上飞");
}
public void move() {
super.move();
fly();
}
}
//具体的装饰角色
class WaterCar extends SuperCar{
public WaterCar(ICar icar) {
super(icar);
}
public void swing() {
System.out.println("在水上游");
}
public void move() {
super.move();
swing();
}
}
//具体的装饰角色
class AICar extends SuperCar{
public AICar(ICar icar) {
super(icar);
}
public void Automove() {
System.out.println("AI控制跑");
}
public void move() {
super.move();
Automove();
}
}
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}