Design Pattern:
Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
模式:超级工厂->create->工厂->create->物品
首先创建两个接口 Shape,Color
public interface Shape {
void draw();
}
public interface Color {
void fill();
}
创建具体的类来实现Shape,Color
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("draw Rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("draw Circle");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("fill green");
}
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("fill red");
}
}
创建类的工厂
/**
* 工厂的抽象
*/
public abstract class AbstractFactory {
public abstract Color getColorFromFactory(String color);
public abstract Shape getShapeFromFactory(String shape);
}
public class ColorFactory extends AbstractFactory{
@Override
public Color getColorFromFactory(String color){
Color col = null;
switch (color){
case "red":col= new Red();break;
case "green":col= new Green();break;
}
return col;
}
@Override
public Shape getShapeFromFactory(String shape) {
return null;
}
}
public class ShapeFactory extends AbstractFactory {
@Override
public Color getColorFromFactory(String color) {
return null;
}
@Override
public Shape getShapeFromFactory(String shape){
Shape sha = null;
switch (shape){
case "rectangle":sha = new Rectangle();break;
case "circle":sha = new Circle();break;
}
return sha;
}
}
创建工厂的超级工厂
/**
* 根据factory字段名 返回具体那种工厂
*/
public class FactoryProducer {
String factory;
public FactoryProducer(String fact) {
this.factory = fact;
}
public AbstractFactory getFactory(){
AbstractFactory af = null;
switch (factory){
case "color":af = new ColorFactory();break;
case "shape":af = new ShapeFactory();break;
}
return af;
}
public String getFact() {
return factory;
}
public void setFact(String fact) {
this.factory = fact;
}
}
实验的开始
public class AbstractFactoryDemo {
public static void main(String[] args) {
String str = "color";
FactoryProducer fp = new FactoryProducer(str);
AbstractFactory af = fp.getFactory();
String green = "green";
Color color = af.getColorFromFactory(green);
color.fill();
}
}
结果
