装饰者模式(Decorator Pattern)
程序员文章站
2022-07-13 22:05:21
...
类图
ICar.java
public interface ICar {
//汽车有跑的功能
public void run();
}
Honda.java
public class Honda implements ICar {
@Override
public void run() {
System.out.println("本田有跑的功能");
}
}
Volvo.java
public class Volvo implements ICar{
@Override
public void run() {
System.out.println("沃尔沃有跑的功能");
}
}
MusicDecorator.java
public abstract class MusicDecorator
implements ICar{ //实现原有的接口
protected ICar iCar; //持有原有的接口
public MusicDecorator(ICar iCar){
this.iCar = iCar;
}
@Override
public void run() {
iCar.run();
}
}
MusicDecoratorImpl.java
//装饰者具体实现
public class MusicDecoratorImpl extends MusicDecorator {
public MusicDecoratorImpl(ICar iCar){
super(iCar);
}
@Override
public void run() {
iCar.run();
playMuisc();
}
public void playMuisc(){
System.out.println("播放音乐");
}
}
TVDecorator.java
public abstract class TVDecorator implements ICar{
protected ICar iCar;
public TVDecorator(ICar iCar){
this.iCar = iCar;
}
@Override
public void run() {
iCar.run();
}
}
TVDecoratorImpl.java
public class TVDecoratorImpl extends TVDecorator {
public TVDecoratorImpl(ICar iCar) {
super(iCar);
}
@Override
public void run() {
iCar.run();
playTv();
}
public void playTv(){
System.out.println("播放电视");
}
}
TestMain.java
public class TestMain {
//车只有跑的功能
@Test
public void hondaRunTest(){
ICar iCar = new Honda();
iCar.run();
}
//为本田汽车添加音乐和看电视功能
@Test
public void testHonda(){
ICar honda = new Honda(); //本田汽车
honda = new MusicDecoratorImpl(honda); //音乐功能
honda = new TVDecoratorImpl(honda); //看电视功能
honda.run();
}
//为沃尔沃汽车添加音乐和看电视功能
@Test
public void testVolvo(){
ICar volvo = new Volvo();
volvo = new MusicDecoratorImpl(volvo);
volvo = new TVDecoratorImpl(volvo);
volvo.run();
}
}
输出
本田有跑的功能
播放音乐
播放电视