装饰模式

来源:互联网 发布:阿里云主机多少钱 编辑:程序博客网 时间:2024/05/19 02:45

百度百科


装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。

在装饰模式中的各个角色有:

  • 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
  • 具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
  • 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
  • 具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。

本例子以游戏战舰世界为例子。

原始接口船(抽象构件(Component)角色)

public interface Ship {    public void move();}

战舰(具体构件(Concrete Component)角色)

public class WarShip implements Ship{    @Override    public void move() {        System.out.println("移动");    }}

给战舰添加各种功能的工厂(装饰(Decorator)角色)

public class Factory implements Ship{    private Ship ship;   //既然要给船添加功能,必须要开来一条船    public Factory(Ship ship) {        this.ship = ship;    }    @Override    public void move() {        ship.move();    }}

添加信号旗(具体装饰(Concrete Decorator)角色)

public class Weft extends Factory{    @Override    public void move() {        super.move();        fire();    }    public void fire() {        System.out.println("增加炮火");    }    public Weft(Ship ship) {        super(ship);    }}

添加涂装(具体装饰(Concrete Decorator)角色)

public class Painting extends Factory{    @Override    public void move() {        super.move();        painting();    }    public void painting() {        System.out.println("增加隐蔽性 ");    }    public Painting(Ship ship) {        super(ship);    }}

客户端方法

public class Main {    public static void main(String[] args) {        Ship ship = new WarShip();        Ship war = new Painting(new Weft(ship));        war.move();    }}
原创粉丝点击