生活随笔
收集整理的這篇文章主要介紹了
java设计模式之五(原型模式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是原型模式?
原型模式(Prototype Pattern)是用于創建重復的對象,同時又能保證性能。這種類型的設計模式屬于創建型模式,它提供了一種創建對象的最佳方式。
當我們程序中有幾個相似但又不太一樣的對象時,就可以使用原型模式。簡單一些說的話,就是通過深拷貝的方法用原型實例指定創建對象的種類。
Java 自帶的原型模式基于內存二進制流的復制,在性能上比直接 new 一個對象更加優良。
圖示
我們可以舉個例子,比如現在有三個形狀對象,圓形(Circle),正方形(Square),長方形(Rectangle)。現在我們想要通過原型模式創建這三個對象,那就需要有一個原型實例 :形狀(Shape),讓它實現java的接口類Cloneable,并且重寫克隆方法clone()。
然后我們定義一個類 ShapeCache,該類把 shape 對象存儲在一個 Hashtable 中,并在請求的時候返回它們的克隆。最后通過PrototypePatternDemo 類使用 ShapeCache 類來獲取 Shape 對象。
實現
步驟1
public abstract
class Shape implements Cloneable{private String id
;protected String type
;abstract
void draw();public String
getId() {return id
;}public void setId(String id) {this.id
= id
;}public String
getType() {return type
;}public Object
clone(){Object clone
= null;try{clone
= super.clone();} catch (CloneNotSupportedException e
){e
.printStackTrace();}return clone
;}}
步驟2
實現具體對象 圓形(Circle),正方形(Square),長方形(Rectangle)
public class Circle extends Shape{public Circle(){type
= "Circle";}@Override
void draw() {System
.out
.println("Inside Circle::draw() method");}
}
public class Square extends Shape{public Square(){type
= "Square";}@Override
void draw() {System
.out
.println("Inside Square::draw() method");}
}
public class Rectangle extends Shape{public Rectangle(){type
= "Rectangle";}@Override
void draw() {System
.out
.println("Inside Rectangle::draw() method");}
}
步驟3
通過調用原型對象克隆方法,創建指定對象
import java
.util
.Hashtable
;public class ShapeCache {private static Hashtable
<String
, Shape
> shapeMap
= new Hashtable<String
, Shape
>();public static Shape
getShape(String shapeId){Shape shapeCache
= shapeMap
.get(shapeId
);return (Shape
)shapeCache
.clone();}public static void loadCache(){Circle circle
= new Circle();circle
.setId("1");shapeMap
.put(circle
.getId(), circle
);Square square
= new Square();square
.setId("2");shapeMap
.put(square
.getId(), square
);Rectangle rectangle
= new Rectangle();rectangle
.setId("3");shapeMap
.put(rectangle
.getId(), rectangle
);}
}
步驟4
main()方法檢查結果
public class PrototypePattenDemo {public static void main(String[] args) {ShapeCache
.loadCache();Shape cloneShape1
= (Shape
)ShapeCache
.getShape("1");System
.out
.println("Shape: "+ cloneShape1
.getType());System
.out
.println("Shape: "+ cloneShape1
.getId());cloneShape1
.draw();System
.out
.println("------------------------------");Shape cloneShape2
= (Shape
)ShapeCache
.getShape("2");System
.out
.println("Shape: "+ cloneShape2
.getType());System
.out
.println("Shape: "+ cloneShape2
.getId());cloneShape2
.draw();System
.out
.println("------------------------------");Shape cloneShape3
= (Shape
)ShapeCache
.getShape("3");System
.out
.println("Shape: "+ cloneShape3
.getType());System
.out
.println("Shape: "+ cloneShape3
.getId());cloneShape3
.draw();System
.out
.println("------------------------------");}
}
總結
以上是生活随笔為你收集整理的java设计模式之五(原型模式)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。