什么是装饰模式?
在不改变对象已有功能的前提下,对已有对象进行功能的扩展。
示例场景描述
房子为毛呸房,需对毛呸房进行装修,先装地板在装门。
示例图
图片.png示例代码
1.创建抽象功能类
public class DecoratorBehavior {
public void decoratorHouse(){
}
}
2.创建被装饰类
public class RoughHome extends DecoratorBehavior {
@Override
public void decoratorHouse() {
System.out.println("1>>>>>>>>>>>>>>>购买毛呸房");
}
}
3.创建抽象装饰类
public abstract class DecoratorWork extends DecoratorBehavior{
protected DecoratorBehavior decoratorBehavior;
public DecoratorWork(DecoratorBehavior decoratorBehavior) {
this.decoratorBehavior = decoratorBehavior;
}
public DecoratorWork() {
}
@Override
public void decoratorHouse() {
if(decoratorBehavior!=null){
decoratorBehavior.decoratorHouse();
}
}
}
4.创建具体装饰类-地板和门
public class Floor extends DecoratorWork{
public Floor(DecoratorBehavior decoratorBehavior) {
super(decoratorBehavior);
}
public Floor() {
}
@Override
public void decoratorHouse() {
super.decoratorHouse();
System.out.println("2>>>>>>>>>>>>>>>>>>安装地板");
}
}
public class Door extends DecoratorWork{
public Door(DecoratorBehavior decoratorBehavior) {
super(decoratorBehavior);
}
public Door() {
}
@Override
public void decoratorHouse() {
super.decoratorHouse();
System.out.println("3>>>>>>>>>>>>>>>>>>>>>安装门");
}
}
5.启动类
public class Test {
public static void main(String[] args) {
RoughHome roughHome = new RoughHome();
Floor floor = new Floor(roughHome);
Door door = new Door(floor);
door.decoratorHouse();
}
}
6.运行结果
图片.png
网友评论