原型模式
本文最后更新于 685 天前,其中的信息可能已经有所发展或是发生改变。

Prototype Pattern 对象创建型模式

意图

用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象

结构

其中:

  • Prototype 声明一个复制自身的接口
  • ConcretePrototype 实现一个复制自身的操作
  • Client 让一个原型复制自身从而创建一个新的对象

适用性

Prototype 模式适用于:

  • 当一个系统应该独立于它的产品创建、构成和表示时
  • 当要实例化的类是在运行时刻指定时,例如,通过动态装载
  • 为了避免创建一个与产品类层次平行的工厂类层次时
  • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们,可能比每次用合适的状态手工实例化该类更方便一些

例子 1

public class main{
Product p1 = new Product(2023, 3.03);
System.out.println(p1.getId() + " " + p1.getPrice());
// Product p2 = new Product(2023, 3.03);
Product p2 = (Product) p1.Clone();
System.out.println(p2.getId() + " " + p2.getPrice());
}
interface Prototype{
public Object Clone();
}
class Product implements Prototype{
private int id;
private double price;
public Product(){}
public Product(int id, double price){
this.id = id;
this.price = price;
}
public int getId(){
return this.id;
}
public double getPrice(){
return this.price;
}
public void setId(int id){
this.id = id;
}
public void setPrice(double price){
this.price = price;
}
@Override
public Object Clone(){
Product object = new Product();
object.id = this.id;
object.price = this.price;
return object;
}
}

例子 2 (使用官方接口)

public class main{
Product p1 = new Product(2023, 3.03);
System.out.println(p1.getId() + " " + p1.getPrice());
// Product p2 = new Product(2023, 3.03);
Product p2 = (Product) p1.clone();
System.out.println(p2.getId() + " " + p2.getPrice());
}
// 去除
// interface Prototype{
// public Object Clone();
// }
// 实现接口
class Product implements Cloneable{
private int id;
private double price;
public Product(){}
public Product(int id, double price){
this.id = id;
this.price = price;
}
public int getId(){
return this.id;
}
public double getPrice(){
return this.price;
}
public void setId(int id){
this.id = id;
}
public void setPrice(double price){
this.price = price;
}
// 重写方法
@Override
public Object clone(){
return super.clone();
}
}
本文链接:原型模式
本文章由 yexca 采用 知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议 进行许可,转载请注明出处。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇