JAVA設計模式之工廠模式之抽象工廠模式


public class AbstractFactoryTest {

	@Test
	public void testFillColor(){
		AbstractFactory colorFactory=new ColorFactory();
		Color red=colorFactory.getColor("Red");
		assertEquals("Red fill",red.fill());
	}
	
	@Test
	public void testDrawShape(){
		AbstractFactory shapeFactory=new ShapeFactory();
		Shape circle=shapeFactory.getShape("Circle");
		assertEquals("Circle draw",circle.draw());
	}
}
/**
 * 工廠方法模式針對的是一個產品等級結構;而抽象工廠模式則是針對的多個產品等級結構
 */
public abstract class AbstractFactory {
     public abstract Color getColor(String color);
     public abstract Shape getShape(String shape);
}
public interface Color {

	String fill();
}
public interface Shape {

	String draw();
}

public class ColorFactory extends AbstractFactory {

	@Override
	public Color getColor(String color) {
	
		if(null == color){
			return null;
		}
		if("Red".equalsIgnoreCase(color)){
			return new Red();
		}else if("Black".equalsIgnoreCase(color)){
			return new Black();
		}else if("White".equalsIgnoreCase(color)){
			return new White();
		}
		return null;
	}

	@Override
	public Shape getShape(String shape) {

		return null;
	}
}
public class ShapeFactory extends AbstractFactory  {


	@Override
	public Shape getShape(String shape) {
	    if(null == shape){
	    	return null;
	    }
	    if("Circle".equalsIgnoreCase(shape)){
	    	return new Circle();
	    }else if("Square".equalsIgnoreCase(shape)){
	    	return new Square();
	    }else if("Rectangle".equalsIgnoreCase(shape)){
	    	return new Rectangle();
	    }
	    
		return null;
	}
  
	@Override
	public Color getColor(String color) {
		return null;
	}
}
備註:Color Shape的具體實現略

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章