抽象工厂模式
void draw();
}
步骤 2
创建实现接口的实体类。
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
步骤 3
为颜色创建一个接口。
Color.java
public interface Color {
void fill();
}
步骤 4
创建实现接口的实体类。
Red.java
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fille() method.");
}
}
Green.java
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fille() method.");
}
}
Blue.java
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fille() method.");
}
}
步骤 5
为 Color 和 Shape 对象创建抽象类来获取工厂。
AbstractFactory.java
public abstract class AbstractFactory {
abstract Shape getSh
ape(String shape);
abstract Color getColor(String color);
}
步骤 6
创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象。
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
@Override
Shape getShape(String shape) {
if (shape == null) {
return null;
}
shape = shape.toLowerCase();
switch (shape) {
case "circle":
return new Circle();
case "rectangle":
return new Rectangle();
case "square":
return new Square();
default:
return null;
}
}
@Override
Color getColor(String color) {
return null;
}
}
ColorFactory.java
public class ColorFactory extends AbstractFactory {
@Override
Shape getShape(String shape) {
return null;
}
@Override
Color getColor(String color) {
if (color == null) {
return null;
}
color = color.toLowerCase();
switch (color) {
case "red":
return new Red();
case "blue":
return new Blue();
case "green":
return new Green();
default:
return null;
}
}
}
步骤 7
创建一个工厂创造器/生成器类,通过传递形状或颜色信息来获取工厂。
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
if (choice == null) {
return null;
}
if ("shape".equalsIgnoreCase(choice)) {
return new ShapeFactory();
} else if ("color".equalsIgnoreCase(choice)) {
return new ColorFactory();
} else {
return null;
}
}
}
步骤 8
使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象。
AbstractFactoryPatternDemo.java
评论