八、装饰模式

    xiaoxiao2022-07-15  181

    装饰模式

    1、什么是装饰模式2、装饰模式的结构3、装饰模式的角色和职责4、代码实现

    1、什么是装饰模式

    2、装饰模式的结构

    3、装饰模式的角色和职责

    抽象组件角色: 一个抽象接口,是被装饰类和装饰类的父接口。具体组件角色:为抽象组件的实现类。抽象装饰角色:包含一个组件的引用,并定义了与抽象组件一致的接口。具体装饰角色:为抽象装饰角色的实现类。负责具体的装饰。

    4、代码实现

    package com.example.demo03; public interface Car { public void show(); public void run(); } package com.example.demo03; public abstract class CarDecorator implements Car{ private Car car; public CarDecorator(Car car){ this.car = car; } public abstract void show(); public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } } package com.example.demo03; public class FlyCarDecorator extends CarDecorator{ public FlyCarDecorator(Car car) { super(car); } @Override public void show() { this.getCar().show(); this.fly(); } public void fly(){ System.out.println("可以飞"); } @Override public void run() { // TODO Auto-generated method stub } } package com.example.demo03; public class SwimCarDecorator extends CarDecorator{ public SwimCarDecorator(Car car) { super(car); } @Override public void show() { this.getCar().show(); this.swim(); } public void swim(){ System.out.println("可以游"); } @Override public void run() { // TODO Auto-generated method stub } } package com.example.demo03; public class RunCar implements Car{ @Override public void show() { this.run(); } public void run(){ System.out.println("可以跑"); } } package com.example.demo03; import org.junit.Test; public class MainClass { @Test public void test01(){ Car flyCar = new RunCar(); CarDecorator carDecorator = new FlyCarDecorator(flyCar); carDecorator.show(); carDecorator = new SwimCarDecorator(flyCar); carDecorator.show(); } @Test public void test02(){ Car car = new RunCar(); car.show(); System.out.println("------------------------------------"); CarDecorator fly = new FlyCarDecorator(car); fly.show(); System.out.println("------------------------------------"); CarDecorator swimFly = new SwimCarDecorator(fly); swimFly.show(); } @Test public void test03(){ Car car = new RunCar(); CarDecorator fly = new FlyCarDecorator(car); CarDecorator swimFly = new SwimCarDecorator(fly); swimFly.show(); } }
    最新回复(0)