package com.henu.factory.abstractfactory;
public interface Color {
void fill();
}
package com.henu.factory.abstractfactory;
public class Blue implements Color{
@Override
public void fill() {
System.out.println("color id blue");
}
}
package com.henu.factory.abstractfactory;
public class Red implements Color{
@Override
public void fill() {
System.out.println("color id red ");
}
}
package com.henu.factory.abstractfactory;
public class Green implements Color{
@Override
public void fill() {
System.out.println("color is green");
}
}
package com.henu.factory.abstractfactory;
public interface Shape {
void draw();
}
package com.henu.factory.abstractfactory;
public class Square implements Shape{
@Override
public void draw() {
System.out.println("this id Square.....");
}
}
package com.henu.factory.abstractfactory;
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("this is Circle ");
}
}
package com.henu.factory.abstractfactory;
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
package com.henu.factory.abstractfactory;
public class ColorFactory extends AbstractFactory{
@Override
Color getColor(String color) {
if(color==null) return null;
if(color.equals("red")) return new Red();
if(color.equals("green")) return new Green();
if(color.equals("blue")) return new Blue();
return null;
}
@Override
Shape getShape(String shape) {
// TODO Auto-generated method stub
return null;
}
}
package com.henu.factory.abstractfactory;
public class ShapeFactory extends AbstractFactory{
@Override
Color getColor(String color) {
return null;
}
@Override
Shape getShape(String shape) {
if(shape==null){
return null;
}
if(shape.equals("circle")){
return new Circle();
}else if(shape.equals("rectangle")){
return new Rectangle();
}else if(shape.equals("square")){
return new Square();
}
return null;
}
}
package com.henu.factory.abstractfactory;
public class FactoryProducer {
public static AbstractFactory getFactory(String type){
if(type==null) return null;
if(type.equalsIgnoreCase("shape")){
return new ShapeFactory();
}else if(type.equalsIgnoreCase("color")){
return new ColorFactory();
}
return null;
}
}
package com.henu.factory.abstractfactory;
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
//获取形状的工厂类
AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");
Shape shape1 = shapeFactory.getShape("circle");
shape1.draw();
Shape shape2 = shapeFactory.getShape("rectangle");
shape2.draw();
Shape shape3 = shapeFactory.getShape("square");
shape3.draw();
AbstractFactory colorFactory = FactoryProducer.getFactory("color");
Color color1 = colorFactory.getColor("red");
color1.fill();
}
}
抽象工厂模式
最新推荐文章于 2024-07-23 16:12:42 发布