實作方法
我們將建立一個Shape介面和實作Shape介面的具體類別。一個工廠類別ShapeFactory會在下一步定義。
FactoryPatternDemo這是一個示範類,將使用ShapeFactory來取得一個Shape物件。它會將資訊(CIRCLE/RECTANGLE/SQUARE)傳遞給ShapeFactory以取得所需的物件類型。
實現工廠模式的結構如下圖所示-
java-61.jpg
第1步
# 建立一個介面-
# Shape.java
# publicinterfaceShape{
voiddraw();
}
# 第2步
# 建立實作相同介面的具體類別。如下所示幾個類別-
Rectangle.java
publicclassRectangleimplementsShape{
# @Override
# publicvoiddraw(){
System.out.println("InsideRectangle::draw()method.");
# }
# }
# Square.java
# publicclassSquareimplementsShape{
# @Override
# publicvoiddraw(){
System.out.println("InsideSquare::draw()method.");
}
# }
# Circle.java
publicclassCircleimplementsShape{
# @Override
# publicvoiddraw(){
System.out.println("InsideCircle::draw()method.");
# }
# }
# 第3步
# 創建工廠根據給定的資訊產生具體類別的物件。
ShapeFactory.java
publicclassShapeFactory{
//usegetShapemethodtogetobjectoftypeshape
# publicShapegetShape(StringshapeType){
if(shapeType==null){
# returnnull;
}
# if(shapeType.equalsIgnoreCase("CIRCLE")){
returnnewCircle();
# }elseif(shapeType.equalsIgnoreCase("RECTANGLE")){
# returnnewRectangle();
# }elseif(shapeType.equalsIgnoreCase("SQUARE")){
# returnnewSquare();
}
# returnnull;
}
# }
# 第4步
# 使用工廠透過傳遞類型等資訊來取得特定類別的物件。
FactoryPatternDemo.java
publicclassFactoryPatternDemo{
publicstaticvoidmain(String[]args){
ShapeFactoryshapeFactory=newShapeFactory();
# //getanobjectofCircleandcallitsdrawmethod.
# Shapeshape1=shapeFactory.getShape("CIRCLE");
//calldrawmethodofCircle
# shape1.draw();
# //getanobjectofRectangleandcallitsdrawmethod.
# Shapeshape2=shapeFactory.getShape("RECTANGLE");
//calldrawmethodofRectangle
# shape2.draw();
# //getanobjectofSquareandcallitsdrawmethod.
# Shapeshape3=shapeFactory.getShape("SQUARE");
//calldrawmethodofcircle
# shape3.draw();
# }
# }
# 第5步
# 驗證輸出結果如下-
InsideCircle::draw()method.
InsideRectangle::draw()method.
InsideSquare::draw()method.
以上是Java工廠設計模式的程式碼怎麼寫的詳細內容。更多資訊請關注PHP中文網其他相關文章!