【Design Pattern】Abstract Factory

3752 ワード

1.製品類
製品はColorとShapeの2つのシリーズがあり、各シリーズには2つの具体的な製品があります.
package AbstractFactory;

public interface Color {
	
	public void fill();
	
}
package AbstractFactory;

public class Red implements Color{

	@Override
	public void fill() {
		System.out.println("Fill Red!");
		
	}

}
package AbstractFactory;

public class Blue implements Color{

	@Override
	public void fill() {
		System.out.println("Fill Blue!");
		
	}
	
}
package AbstractFactory;

public interface Shape {

	public void draw();
}
package AbstractFactory;

public class Square implements Shape{

	@Override
	public void draw() {
		System.out.println("Draw a square!");		
	}

}
package AbstractFactory;

public class Circle implements Shape{

	@Override
	public void draw() {
		System.out.println("Draw a circle!");		
	}
}

2.抽象工場類
指定した色または指定した形状の製造に使用
package AbstractFactory;

public abstract class AbstractFactory {
	   abstract Color getColor(String color);
	   abstract Shape getShape(String shape) ;
	
}

3.抽象工場実現クラス
package AbstractFactory;

public class ColorFactory extends AbstractFactory{

	@Override
	Color getColor(String color) {
		if(color == null){
	         return null;
	      }		
	      if(color.equalsIgnoreCase("RED")){
	         return new Red();
	      }else if(color.equalsIgnoreCase("BLUE")){
	         return new Blue();
	      }
	      return null;
	}

	@Override
	Shape getShape(String shape) {
		// TODO Auto-generated method stub
		return null;
	}

}
package AbstractFactory;

public class ShapeFactory extends AbstractFactory{

	@Override
	Color getColor(String color) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	Shape getShape(String shapeType) {
		if(shapeType == null){
	         return null;
	      }		
	      if(shapeType.equalsIgnoreCase("CIRCLE")){
	         return new Circle();
	      }else if(shapeType.equalsIgnoreCase("SQUARE")){
	         return new Square();
	      }
	      return null;
	}
}

4.工場生成クラス
package AbstractFactory;

public class FactoryProducer {
	
	public AbstractFactory getFactory(String type){
		if(type.equalsIgnoreCase("Color")){
			return new ColorFactory();
		}else if(type.equalsIgnoreCase("")){
			return new ShapeFactory();
		}
		return null;	
	}
}

5.Demo
package AbstractFactory;

public class AbastractFactoryDemo {
	
	public static void main(String[] args) {
		AbstractFactory shapefactory = FactoryProducer.getFactory("Shape");
		Shape circle = shapefactory.getShape("circle");
		circle.draw();
		
		AbstractFactory colorfactory = FactoryProducer.getFactory("Color");
		Color red = colorfactory.getColor("red");
		red.fill();
	}

}