設計模式總結(5)
阿新 • • 發佈:2018-11-03
設計模式總結(5)
工廠模式
工廠模式是java中最常用的設計模式之一。這種型別的設計模式屬於建立型模式,它提供了一種建立物件的最佳方式。在工廠模式中,我們在建立物件時不會對客戶端暴露建立邏輯,並且是通過使用一個共同的介面來指向新建立的物件。比如hibernate框架在更換資料庫時只需要更換方言和驅動即可。
**優點:**對外隱藏實現邏輯,呼叫不同的物件只需要知道類名即可;拓展性高,增加相似功能時只需要拓展工廠類和具體實現類。
**缺點:**每次增加一個功能,都要相應的拓展工廠類和具體實現類,使得類的個數成倍增加,同時增加具體類的依賴。
定義一個所有實現類需要實現的介面,這些實現類都具有這個功能,只是實現的方式不同:
interface Shape {
void draw();
}
定義三個實現相似功能的實現類:
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Draw rectangle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Draw square " );
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Draw circle ");
}
}
定義工廠類,具體實現哪個類由工廠決定:
class ShapeFactory {
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;
}
}
測試:
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//獲取 Circle 的物件,並呼叫它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//呼叫 Circle 的 draw 方法
shape1.draw();
//獲取 Rectangle 的物件,並呼叫它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//呼叫 Rectangle 的 draw 方法
shape2.draw();
//獲取 Square 的物件,並呼叫它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//呼叫 Square 的 draw 方法
shape3.draw();
}
}
結果:
Draw circle
Draw rectangle
Draw square