赞
踩
工厂模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。在Java中,工厂模式可以通过接口和实现类来实现。比如我们建一个外形工厂,工厂提供对外的获取外形方法,传入不同的参数即可获取不同的外形。如图所示:
以下是工厂模式的详细说明:
public interface Shape {
void draw();
}
public class Circle implements Shape { @Override public void draw() { System.out.println("画一个圆形"); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("画一个矩形"); } } public class Square implements Shape { @Override public void draw() { System.out.println("画一个正方形"); } }
public class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("RECTANGLE")) { return new Rectangle(); } else if (shapeType.equalsIgnoreCase("SQUARE")) { return new Square(); } return null; } }
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("CIRCLE");
circle.draw();
Shape rectangle = shapeFactory.getShape("RECTANGLE");
rectangle.draw();
Shape square = shapeFactory.getShape("SQUARE");
square.draw();
}
}
工厂模式适用于多种场景,尤其当需要创建一组相关或不相关的对象时,或者在需要将对象的创建和使用分离的情况下。以下是一些具体的应用场景:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。