【Design Pattern】Abstract Factory

1.产品类
产品有Color和Shape两个系列,每个系列有两个具体的产品
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();
	}

}

你可能感兴趣的:(design pattern)