這期內容當中小編將會給大家帶來有關運用Java的工廠設計模式,以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
工廠模式是Java中最常用的設計模式之一。 這種類型的設計模式屬于創建模式,因為此模式提供了創建對象的最佳方法之一。
在工廠模式中,我們沒有創建邏輯暴露給客戶端創建對象,并使用一個通用的接口引用新創建的對象。
實現方法
我們將創建一個Shape接口和實現Shape接口的具體類。 一個工廠類ShapeFactory會在下一步中定義。
FactoryPatternDemo這是一個演示類,將使用ShapeFactory來獲取一個Shape對象。它會將信息(CIRCLE/RECTANGLE/SQUARE)傳遞給ShapeFactory以獲取所需的對象類型。
實現工廠模式的結構如下圖所示 -

第1步
創建一個接口-
Shape.java
public interface Shape {
void draw();
}第2步
創建實現相同接口的具體類。如下所示幾個類 -
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}第3步
創建工廠根據給定的信息生成具體類的對象。
ShapeFactory.java
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}第4步
使用工廠通過傳遞類型等信息來獲取具體類的對象。
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of circle
shape3.draw();
}
}第5步
驗證輸出結果如下-
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
上述就是小編為大家分享的運用Java的工廠設計模式,如果您也有類似的疑惑,不妨參照上述方法進行嘗試。如果想了解更多相關內容,請關注億速云行業資訊。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。