设计模式:抽象工厂、备忘录、组合模式

1.抽象工厂模式(Abstract Factory Pattern)

目的: 抽象工厂模式是一种创建型设计模式,它提供一个接口,用于创建相关或依赖对象家族的一个或多个系列的产品,而无需指定具体产品类。这样可以使客户端独立于具体产品的创建过程,同时使得易于更换整体产品族。

结构

  • AbstractFactory(抽象工厂):声明创建一组相关或相互依赖对象的接口,让客户端可以使用这些对象而无需指定它们的具体类型。
  • ConcreteFactory(具体工厂):实现抽象工厂接口,生成一组具体产品对象。
  • Product(抽象产品):定义产品的接口,它是所有具体产品必须实现的接口。
  • ConcreteProduct(具体产品):实现了抽象产品接口,是实际生产出来的产品。

示例场景: 操作系统界面元素工厂,可以创建不同风格(如Windows、Mac OS、Linux)的按钮、窗口等界面组件。

// 抽象产品接口
interface Color {
    void fill();
}

interface Shape {
    void draw();
}

// 具体产品
class RedColor implements Color {
    @Override
    public void fill() {
        System.out.println("填充红色");
    }
}

class BlueColor implements Color {
    @Override
    public void fill() {
    System.out.println("填充蓝色");
    }

// 形状
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}

class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("绘制正方形");
    }

// 抽象工厂
interface ColorFactory {
    Color getColor();
}

interface ShapeFactory {
    Shape getShape();
}

// 具体工厂
class RedColorFactory implements ColorFactory {
    @Override
    public Color getColor() {
        return new RedColor();
    }
}

class BlueColorFactory implements ColorFactory {
    @Override
    public Color getColor() {
        return new BlueColor();
    }

class CircleFactory implements ShapeFactory {
    @Override
    public Shape getShape() {
        return new Circle();
    }
}

class SquareFactory implements ShapeFactory {
    @Override
    public Shape getShape() {
        return new Square();
    }

// 客户端代码
public class Client {
    public static void main(String[] args) {
        ColorFactory redColorFactory = new RedColorFactory();
        ShapeFactory circleFactory = new CircleFactory();

        Color color = redColorFactory.getColor();
        Shape shape = circleFactory.getShape();

        color.fill();
        shape.draw();
    }
}

2.备忘录模式(Memento Pattern)

目的: 备忘录模式是一种行为设计模式,它提供了一种在不破坏封装性的前提下,捕获并外部化对象状态的方法,以便在稍后时刻恢复对象状态。

结构

  • Originator(发起人):创建一个备忘录,可以利用备忘录恢复到先前的状态。通常包含一些重要的业务数据。
  • Memento(备忘录):存储发起人的内部状态。为了保护发起人的隐私,备忘录通常只提供有限的接口供发起人访问。
  • Caretaker(管理者):负责保存和恢复发起人的状态,但不能对备忘录的内容进行任何操作,只能将其传递给发起人。

示例场景: 文本编辑器的撤销功能,每次编辑操作后,编辑器都会创建一个包含当前文档内容的备忘录,之后可以使用备忘录恢复到之前的状态。

// 原始类(Originator)
class GameSnapshot {
    private int score;
    private int level;
    
    public GameSnapshot(int score, int level) {
        this.score = score;
        this.level = level;
    }

    public int getScore() {
        return score;
    }

    public int getLevel() {
        return level;
    }

    // 创建备忘录
    public Memento saveGame() {
        return new Memento(score, level);
    }

    // 恢复游戏状态
    public void restoreGame(Memento memento) {
        this.score = memento.getScore();
        this.level = memento.getLevel();
    }
}

// 备忘录(Memento)
class Memento {
    private final int score;
    private final int level;

    public Memento(int score, int level) {
        this.score = score;
        this.level = level;
    }

    public int getScore() {
        return score;
    }

    public int getLevel() {
        return level;
    }
}

// 管理者(Caretaker)
public class GameManager {
    private Memento savedMemento;

    public void saveGame(GameSnapshot game) {
        savedMemento = game.saveGame();
    }

    public void restoreGame(GameSnapshot game) {
        if (savedMemento != null) {
            game.restoreGame(savedMemento);
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        GameSnapshot game = new GameSnapshot(100, 5);
        GameManager manager = new GameManager();

        // 保存游戏状态
        manager.saveGame(game);

        // 改变游戏状态
        game.setLevel(6);
        game.setScore(150);

        // 恢复到之前保存的状态
        manager.restoreGame(game);
    }
}

3.组合模式(Composite Pattern)

目的: 组合模式是一种结构型设计模式,它允许你将对象结构看作一棵树形结构,在这棵树中,个别对象和组合对象对客户来说具有相同的意义。这样,客户可以一致地处理单个对象和对象组合。

结构

  • Component(组件):定义所有对象共有的接口,既可以代表叶子节点(即没有子节点的对象),也可以代表容器节点(即有子节点的对象)。
  • Leaf(叶子节点):实现 Component 接口,代表没有子节点的对象,它的操作通常很简单,不会涉及到递归或子对象。
  • Composite(容器节点):同样实现 Component 接口,但它还包含了额外的方法来管理它的子组件。它可以用来存储和遍历子组件,并调用它们的方法。

示例场景: 文件系统目录结构,目录(Composite)可以包含子目录和文件(Leaf),并且可以对它们进行统一的操作,如添加、删除、显示名称等。

// 抽象组件
abstract class GraphicComponent {
    protected String name;

    public GraphicComponent(String name) {
        this.name = name;
    }

    public abstract void add(GraphicComponent component);
    public abstract void remove(GraphicComponent component);
    public abstract void draw();

    public String getName() {
        return name;
    }
}

// 叶子组件
class Leaf extends GraphicComponent {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(GraphicComponent component) {
        throw new UnsupportedOperationException("Cannot add to a leaf node.");
    }

    @Override
    public void remove(GraphicComponent component) {
        throw new UnsupportedOperationException("Cannot remove from a leaf node.");
    }

    @Override
    public void draw() {
        System.out.println("Drawing " + name);
    }
}

// 容器组件
class Composite extends GraphicComponent {
    private List<GraphicComponent> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(GraphicComponent component) {
        children.add(component);
    }

    @Override
    public void remove(GraphicComponent component) {
        children.remove(component);
    }

    @Override
    public void draw() {
        System.out.println("Drawing " + name);
        for (GraphicComponent child : children) {
            child.draw();
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Composite graphics = new Composite("Graphics");
        graphics.add(new Leaf("Rectangle"));
        graphics.add(new Leaf("Circle"));

        Composite moreGraphics = new Composite("More Graphics");
        moreGraphics.add(new Leaf("Triangle"));
        moreGraphics.add(new Leaf("Line"));

        graphics.add(moreGraphics);

        graphics.draw();
    }
}

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值