JAVA設計模式-1-工廠模式
阿新 • • 發佈:2018-11-12
工廠模式是Java中最常用的設計模式之一。這種型別的設計模式屬於建立模式,因為此模式提供了建立物件的最佳方法之一。
在Factory模式中,我們建立物件而不將建立邏輯暴露給客戶端,並使用公共介面引用新建立的物件。
履行
我們將建立一個Shape介面和實現Shape介面的具體類。工廠類ShapeFactory被定義為下一步。
FactoryPatternDemo,我們的演示類將使用ShapeFactory來獲取Shape物件。它會將資訊(CIRCLE / RECTANGLE / SQUARE)傳遞給ShapeFactory以獲取所需的物件型別。
![工廠模式UML圖](https://www.tutorialspoint.com/design_pattern/images/factory_pattern_uml_diagram.jpg)
步驟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 { @Overridepublic 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 classShapeFactory { //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
使用Factory通過傳遞型別等資訊來獲取具體類的物件。
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 square shape3.draw(); } }
第5步
驗證輸出。
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.