JAVA設計模式之工廠模式之簡單工廠模式

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());
		
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章