工厂模式主要是避免new所带来的依赖,这样可以在应用直接替换对象而不用修改。
实现要点:
1.创建一个Product的类或者接口,Product的子类实现这个接口(或继承这个类);
2.创建一个Factory的类或者接口,Factory的子类实现这个接口(或继承这个类),实现建造对象的方法。
public interface Shape {void draw(); } public class Circle implements Shape {@Overridepublic void draw() {System.out.println("draw circle");} } public class Square implements Shape{public void draw() {System.out.println("draw square");} } public interface ShapeFactory {public Shape make(String shapeName) throws Exception;} public class ShapeFactoryImpl implements ShapeFactory{@Overridepublic Shape make(String shapeName) throws Exception {if (shapeName.equals("Circle")) {return new Circle();} else if (shapeName.equals("Square")) {return new Square();} else {throw new Exception("Shape Factory can't create " + shapeName);}} }public class Test {/*** @param args*/public static void main(String[] args) {ShapeFactory shapeFactory = new ShapeFactoryImpl();Shape circleShape;try {circleShape = shapeFactory.make("Circle");circleShape.draw();} catch (Exception e) {e.printStackTrace();}Shape squareShape;try {squareShape = shapeFactory.make("Square");squareShape.draw();} catch (Exception e) {e.printStackTrace();}} }
Java 类库中的使用范例:
java.util.Calendar – getInstance()
java.util.Calendar – getInstance(TimeZone zone)
java.util.Calendar – getInstance(Locale aLocale)
java.util.Calendar – getInstance(TimeZone zone, Locale aLocale)
java.text.NumberFormat – getInstance()
java.text.NumberFormat – getInstance(Locale inLocale)