设计模式-装饰者模式

mac2024-11-02  41

什么是装饰者模式

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

组成结构

1.Component(抽象组件又叫被装饰对象的基类)

2.ConcreteComponent(具体组件又叫具体被装饰对象)

3. Decorator(装饰者抽象类)

4.ConcreteDecorator(具体装饰者)

 

假设一个场景

在学校门口有一个卖煎饼的早餐车,主要是卖煎饼,可以加鸡蛋,加香肠。现在来了一位顾客,需要煎饼+鸡蛋+香肠

一般实现

package com.design.mode.decorate; public class Origin { public interface Cake { public String getDescription(); public int cost(); } public static class PanCake implements Cake{ @Override public String getDescription() { return "煎饼"; } @Override public int cost() { return 1; } } public static class Egg implements Cake{ @Override public String getDescription() { return "鸡蛋"; } @Override public int cost() { return 5; } } public static class Sausage implements Cake{ @Override public String getDescription() { return "煎饼"; } @Override public int cost() { return 3; } } public static void main(String[] args) { PanCake panCake = new PanCake(); Egg egg = new Egg(); Sausage sausage = new Sausage(); String description = panCake.getDescription() + "+" + egg.getDescription() + "+" + sausage.getDescription(); int cost = panCake.cost() + egg.cost() + sausage.cost(); System.out.println(description); System.out.println(cost); } }

根据以上代码,        

 最终早餐的描述=panCake.getDescription() + egg.getDescription() + sausage.getDescription()

最终早餐的花费=panCake.cost() + egg.cost() + sausage.cost()

如果新增要再加一个鸡蛋,那么早餐的描述和花费都得修改

使用装饰者模式

类结构

代码

package com.design.mode.decorate; public class DecorateMode { public interface Cake{ public String getDescription(); public int cost(); } /** * 煎饼类,也是被装饰者 */ public static class PanCake implements Cake{ @Override public String getDescription() { return "煎饼"; } @Override public int cost() { return 1; } } public static abstract class Decorator implements Cake{ private Cake cake; public Decorator(Cake cake) { this.cake = cake; } @Override public String getDescription() { return cake.getDescription(); } @Override public int cost() { return cake.cost(); } } public static class EggDecorator extends Decorator{ public EggDecorator(Cake cake) { super(cake); } @Override public String getDescription() { return super.getDescription() + "+" + "鸡蛋"; } @Override public int cost() { return super.cost() + 5; } } public static class SausageDecorator extends Decorator{ public SausageDecorator(Cake cake) { super(cake); } @Override public String getDescription() { return super.getDescription() + "+" + "香肠"; } @Override public int cost() { return super.cost() + 3; } } public static void main(String[] args) { PanCake panCake = new PanCake(); SausageDecorator sausageDecorator = new SausageDecorator(panCake); EggDecorator eggDecorator = new EggDecorator(sausageDecorator); System.out.println(eggDecorator.getDescription()); System.out.println(eggDecorator.cost()); } }

优点:在不变动原类方法的情况下,对功能进行了拓展,如果再加一个鸡蛋,只需要在原早餐上在进行鸡蛋修饰就行,方法不用变动。

最新回复(0)