图解设计模式 - Prototype 模式

本文详细介绍了原型模式的概念及其应用场景,通过具体实例展示了如何利用Prototype模式简化对象创建过程,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读书笔记 仅供参考

Prototype 模式

有时会出现“在不指定类名的前提下生成实例”的情况,就是根据实例生成实例,这就是原型模式。
以下情况需要使用原型模式

对象种类繁多,无法将它们整合到一个类中

需要处理的对象太多,如果将它们分别作为一个类,必须要编写许多个类。

难以根据类生产实例

生成实例的过程太过复杂,很难根据类来生成实例,所以需要通过复制来生成新的实例。

想解耦框架与生成的实例

想要生成实例的框架不依赖于具体的类,需要事先“注册”一个“原型”实例,然后复制。(例子中使用了这种方式)

UML 和角色

这里写图片描述

Prototype

负责定义用于复制现有实例来生成新实例的方法

ConcretePrototype

负责实现复制现有实例并生成新实例的方法

Client

负责使用复制实例的方法生成新的实例

例子

例子程序是编写使用多种方式显示文字,例如将字符串放入方框或加上下换线。
Product 接口属于 Prototype 角色,MessageBox 和 UnderlinePen 实现 Product,属于 ConcreteProduct 角色。Manager 类属于 Client 角色。

public interface Product extends Cloneable{
    void use(String s);
    //复制实例的方法
    Product createClone();
}
public class MessageBox implements Product{

    private char decoChar;

    public MessageBox(char decoChar) {
        this.decoChar = decoChar;
    }

    @Override
    public void use(String s) {
        int length = s.getBytes().length;
        for(int i = 0; i < length + 4; i++) {
            System.out.print(decoChar);
        }
        System.out.println();
        System.out.println(decoChar + " " + s + " " + decoChar);
        for(int i = 0; i < length + 4; i++) {
            System.out.print(decoChar);
        }
        System.out.println();
    }

    @Override
    public Product createClone() {
        Product p = null;
        //使用 clone 方法必须继承 Cloneable 接口,否则会抛出异常。
        try {
            p = (Product) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return p;
    }
}
public class UnderlinePen implements Product {
    private char ulChar;

    public UnderlinePen(char ulChar) {
        this.ulChar = ulChar;
    }

    @Override
    public void use(String s) {
        int length = s.getBytes().length;
        System.out.println("\"" + s + "\"");
        System.out.print(" ");
        for(int i = 0; i < length; i++) {
            System.out.print(ulChar);
        }
        System.out.println();
    }

    @Override
    public Product createClone() {
        Product p = null;
        //使用 clone 方法必须继承 Cloneable 接口,否则会抛出异常。
        try {
            p = (Product) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return p;
    }
}
public class Manager {
    private Map<String, Product> showccase = new HashMap<>();
    public void register(String name, Product proto) {
        showccase.put(name, proto);
    }

    public Product create(String protoName) {
        Product p = (Product) showccase.get(protoName);
        return p.createClone();
    }
}

测试代码

public class Main {
    public static void main(String[] args) {
        //准备
        Manager manager = new Manager();
        UnderlinePen underlinePen = new UnderlinePen('~');
        MessageBox mbox = new MessageBox('*');
        MessageBox sbox = new MessageBox('/');
        manager.register("strong message", underlinePen);
        manager.register("warning box", mbox);
        manager.register("slash box", sbox);

        //生成
        Product p1 = manager.create("strong message");
        Product p2 = manager.create("warning box");
        Product p3 = manager.create("slash box");
        p1.use("Hello, world.");
        p2.use("Hello, world.");
        p3.use("Hello, world.");

    }
}

结果
这里写图片描述

UML
这里写图片描述

clone

这里产生新的对象使用了 clone 方法,但是 clone 方法只是浅拷贝,虽然可以重写 clone 方法来实现深拷贝,但是使用 clone 方法是十分危险和麻烦的一件事。详情:http://blog.youkuaiyun.com/wujunyucg/article/details/78524195

Java设计模式是一组经过实践验证的面向对象设计原则和模式,可以帮助开发人员解决常见的软件设计问题。下面是常见的23种设计模式: 1. 创建型模式(Creational Patterns): - 工厂方法模式(Factory Method Pattern) - 抽象工厂模式(Abstract Factory Pattern) - 单例模式(Singleton Pattern) - 原型模式Prototype Pattern) - 建造者模式(Builder Pattern) 2. 结构型模式(Structural Patterns): - 适配器模式(Adapter Pattern) - 桥接模式(Bridge Pattern) - 组合模式(Composite Pattern) - 装饰器模式(Decorator Pattern) - 外观模式(Facade Pattern) - 享元模式(Flyweight Pattern) - 代理模式(Proxy Pattern) 3. 行为型模式(Behavioral Patterns): - 责任链模式(Chain of Responsibility Pattern) - 命令模式(Command Pattern) - 解释器模式(Interpreter Pattern) - 迭代器模式(Iterator Pattern) - 中介者模式(Mediator Pattern) - 备忘录模式(Memento Pattern) - 观察者模式(Observer Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) 4. 并发型模式(Concurrency Patterns): - 保护性暂停模式(Guarded Suspension Pattern) - 生产者-消费者模式(Producer-Consumer Pattern) - 读写锁模式(Read-Write Lock Pattern) - 信号量模式(Semaphore Pattern) - 线程池模式(Thread Pool Pattern) 这些设计模式可以根据问题的特点和需求来选择使用,它们提供了一些可复用的解决方案,有助于开发高质量、可维护且易于扩展的软件系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值