對(duì)工廠模式的形狀實(shí)例進(jìn)行擴(kuò)展粥惧,增加顏色填充功能。
- 形狀和顏色接口
public interface Color {
void fill();
}
------------------------------------------------------
public interface Shape {
void draw();
}
- 顏色實(shí)現(xiàn)類(形狀的實(shí)現(xiàn)類上一篇有)
public class Blue implements Color{
@Override
public void fill() {
System.out.println("fill Blue color!");
}
}
------------------------------------------------------
public class Red implements Color{
@Override
public void fill() {
System.out.println("fill Red color!");
}
}
------------------------------------------------------
public class Yellow implements Color{
@Override
public void fill() {
System.out.println("fill Yellow color!");
}
}
- 為 Color 和 Shape 對(duì)象創(chuàng)建抽象類來(lái)獲取工廠
public interface AbstractFactory {
Color getColor(String color);
Shape getShape(String shape);
}
- 創(chuàng)建擴(kuò)展了 AbstractFactory 的工廠類匆绣,基于給定的信息生成實(shí)體類的對(duì)象
public class ColorFactory implements AbstractFactory{
@Override
public Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
} else if(color.equalsIgnoreCase("YELLOW")){
return new Yellow();
} else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
@Override
public Shape getShape(String shape) {
return null;
}
}
----------------------------------------------------------------------------------
public class ShapeFactory implements AbstractFactory{
@Override
public Color getColor(String color) {
return null;
}
@Override
public Shape getShape(String shape) {
if(shape == null){
return null;
}
if(shape.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shape.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shape.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
- 創(chuàng)建一個(gè)工廠創(chuàng)造器/生成器類驻右,通過(guò)傳遞形狀或顏色信息來(lái)獲取工廠
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
} else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
- 使用 FactoryProducer 來(lái)獲取 AbstractFactory,通過(guò)傳遞類型信息來(lái)獲取實(shí)體類的對(duì)象
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
AbstractFactory colorFatory = FactoryProducer.getFactory("color");
Color red = colorFatory.getColor("red");
red.fill();
Color yellow = colorFatory.getColor("yellow");
yellow.fill();
Color blue = colorFatory.getColor("blue");
blue.fill();
AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw();
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
}
}
- 輸出結(jié)果:
fill Red color!
fill Yellow color!
fill Blue color!
Draw Rectangle!
Draw Circle!
Draw Square!