装饰模式的实例:
思维图:
具体代码:
package com.bjsxt.test10;
//制作蛋糕的接口
public interface MakeCake {
void make();
}
//父类:蛋糕
abstract class Cake implements MakeCake{
@Override
public abstract void make();
}
//子类:巧克力蛋糕
class ChocoCake extends Cake{
@Override
public void make() {
System.out.println("制作一个巧克力蛋糕");
}
}
//子类:抹茶蛋糕
class MoChaCake extends Cake{
@Override
public void make() {
System.out.println("制作一个抹茶蛋糕");
}
}
//修饰的父类
class Decorater implements MakeCake{
//修饰谁?
private MakeCake mc;
public Decorater(MakeCake mc){
this.mc=mc;
}
@Override
public void make() {
mc.make();
}
}
//子类:加口红来修饰
class DecKouHong extends Decorater{
public DecKouHong(MakeCake mc) {
super(mc);
}
@Override
public void make() {
super.make();
add();
}
public void add(){
System.out.println("在蛋糕中塞入一个口红!");
}
}
class DecZuanJie extends Decorater{
public DecZuanJie(MakeCake mc) {
super(mc);
}
@Override
public void make() {
super.make();
add();
}
public void add(){
System.out.println("在蛋糕中加入一个钻戒!");
}
}
class Test{
public static void main(String[] args) {
ChocoCake cc = new ChocoCake();
cc.make();
System.out.println("---------------------------------");
DecKouHong dkh = new DecKouHong(cc);
dkh.make();
System.out.println("---------------------------------");
//重点就在这里:一定要理解清晰
/*
第一步:走有参构造
第二部:就是走父类的make,然后走到修饰的子类中的make(做一个蛋糕,加一个口红),dkh.make就是走口红类中的make方法
第三步:走add方法,加一个钻戒
*/
DecZuanJie dzj = new DecZuanJie(dkh);
dzj.make();
System.out.println("----------------------------------");
//我想买一个带钻戒和口红的抹茶蛋糕
new DecKouHong(new DecZuanJie(new MoChaCake())).make();
}
}
原文:https://www.cnblogs.com/H-scholar/p/14542806.html