public class SimpleShapeFactory {
/**
* 核心:具體的實現由其Shape子類實現,返回其本身Shape對象
* 優點:工廠方法getShape爲靜態方法,可直接調用;
* 根據參數獲取相應對象,無須知道內部實現;
* 缺點:
* 增加產品,需改變工廠類邏輯條件,與開閉原則相違背;
* 一旦該工廠方法出現故障,其他產品受到影響
* @param shapeType
* @return
*/
public static Shape getShape(String shapeType){
if(null == shapeType){
return null;
}
if("CIRCLE".equalsIgnoreCase(shapeType)){
return new Circle();
}else if("Rectangle".equalsIgnoreCase(shapeType)){
return new Rectangle();
}else if("Square".equalsIgnoreCase(shapeType)){
return new Square();
}
return null;
}
}
public interface Shape {
String draw();
}
public class Circle implements Shape{
@Override
public String draw() {
return "Circle draw";
}
}
public class Rectangle implements Shape {
@Override
public String draw() {
return "Rectangle draw";
}
}
public class Square implements Shape{
@Override
public String draw() {
return "Square draw";
}
}
public class SimpleShapeFactoryTest {
@Test
public void testSimpleShapeFactory(){
Shape circle=SimpleShapeFactory.getShape("Circle");
Shape rectangle=SimpleShapeFactory.getShape("Rectangle");
Shape square=SimpleShapeFactory.getShape("Square");
assertEquals("Circle draw",circle.draw());
assertEquals("Rectangle draw",rectangle.draw());
assertEquals("Square draw",square.draw());
}
}