抽象工厂模式

//Main.java
//抽象工厂模式Abstract Factory Pattern属于创建型模式的一种
//简单对比工厂模式,实际上相当于多加了"生产工厂"这一步
//比如circle产品,先构建生产形状的工厂,再让该工厂去生产circle

interface Shape{
	
}

class Rectangle implements Shape{
	public Rectangle(){
		System.out.println("New Rectangle");
	}
}

class Square implements Shape{
	public Square(){
		System.out.println("New Square");
	}
}

class Circle implements Shape{
	public Circle(){
		System.out.println("New Circle");
	}
}

interface Color{
	
}

class Red implements Color{
	public Red(){
		System.out.println("New Red");
	}
}

class Green implements Color{
	public Green(){
		System.out.println("New Green");
	}
}

class Blue implements Color{
	public Blue(){
		System.out.println("New Blue");
	}
}

abstract class AbstractFactory{
	abstract Shape newShape(String shape);
	abstract Color newColor(String color);
}

class ShapeFactory extends AbstractFactory{
	
	public Shape newShape(String shapeType){
		if(shapeType==null)return null;
		if(shapeType.equalsIgnoreCase("RECTANGLE")){
			return new Rectangle();
		}
		if(shapeType.equalsIgnoreCase("SQUARE")){
			return new Square();
		}
		if(shapeType.equalsIgnoreCase("CIRCLE")){
			return new Circle();
		}
		return null;	
	}
	
	public Color newColor(String colorType){
		return null;
	}
}

class ColorFactory extends AbstractFactory{
	
	public Shape newShape(String shapeType){
		return null;
	}
	public Color newColor(String colorType){
		if(colorType==null)return null;
		if(colorType.equalsIgnoreCase("RED")){
			return new Red();
		}
		if(colorType.equalsIgnoreCase("GREEN")){
			return new Green();
		}
		if(colorType.equalsIgnoreCase("BLUE")){
			return new Blue();
		}
		return null;
	}
}

class FactoryFactory{
	public static AbstractFactory getFactory(String factoryType){
		if(factoryType.equalsIgnoreCase("SHAPE")){
			return new ShapeFactory();
		}
		if(factoryType.equalsIgnoreCase("COLOR")){
			return new ColorFactory();
		}
		return null;
	}
}

public class Main{
	
	public static void main(String[] args){
		AbstractFactory shapeFactory=FactoryFactory.getFactory("shape");
		AbstractFactory colorFactory=FactoryFactory.getFactory("color");
		
		Shape shape1=shapeFactory.newShape("rectangle");
		Shape shape2=shapeFactory.newShape("Square");
		Shape shape3=shapeFactory.newShape("circle");
		
		Color color1=colorFactory.newColor("red");
		Color color2=colorFactory.newColor("green");
		Color color3=colorFactory.newColor("blue");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值