純粹學(xué)習(xí)筆記。
-
工廠(chǎng)模式
我們?cè)趧?chuàng)建對(duì)象時(shí),不向客戶(hù)端暴露創(chuàng)建邏輯。主要解決接口選擇的問(wèn)題。
實(shí)現(xiàn):創(chuàng)建一個(gè)shape接口和實(shí)現(xiàn)shape接口的實(shí)體類(lèi)。

Shape.java
public interface Shape{
void draw();
}
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.");
}
}
創(chuàng)建一個(gè)工廠(chǎng),生成基于給定信息的實(shí)體類(lèi)的對(duì)象。
ShapeFactory.java
public class ShapeFactory {
//使用 getShape 方法獲取形狀類(lèi)型的對(duì)象
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;
}
}
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//獲取 Circle 的對(duì)象,并調(diào)用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//調(diào)用 Circle 的 draw 方法
shape1.draw();
//獲取 Rectangle 的對(duì)象,并調(diào)用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//調(diào)用 Rectangle 的 draw 方法
shape2.draw();
//獲取 Square 的對(duì)象,并調(diào)用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//調(diào)用 Square 的 draw 方法
shape3.draw();
}
}