简单工厂模式(Simple Factory)
简单工厂模式又称静态工厂方法模式(Static Factory Method Pattern),是不同工厂方法模式的一个特殊实现。
简单工厂模式的引进
水果接口规定出所有的水果必须实现的接口,包括任何水果类必须具备的方法:种植plant(),生长grow(),收获harvest().如下图:
水果接口源代码:
/** * 水果 * @author Administrator * */public interface Fruit {//生长void grow();//种植void plant();//收获void harvest();}/** * 苹果 * @author Administrator * */public class Apple implements Fruit{private int treeAge;public int getTreeAge() {return treeAge;}public void setTreeAge(int treeAge) {this.treeAge = treeAge;}@Overridepublic void grow() {System.out.println("Apple grow ...");}@Overridepublic void plant() {System.out.println("Apple plant ...");}@Overridepublic void harvest() {System.out.println("Apple harvest ...");}}/** * 葡萄 * @author Administrator * */public class Grape implements Fruit {//是否有籽private boolean seedless;public boolean isSeedless() {return seedless;}public void setSeedless(boolean seedless) {this.seedless = seedless;}@Overridepublic void grow() {System.out.println("Grape grow ...");}@Overridepublic void plant() {System.out.println("Grape plant ...");}@Overridepublic void harvest() {System.out.println("Grape harvest ...");}}/** * 草莓 * @author Administrator * */public class Strawberry implements Fruit {@Overridepublic void grow() {System.out.println("Strawberry grow ...");}@Overridepublic void plant() {System.out.println("Strawberry plant ...");}@Overridepublic void harvest() {System.out.println("Strawberry harvest ...");}}public class FruitGardener {/** * 静态工厂方法 * @param which * @return */public static Fruit factory(String which){if(which.equalsIgnoreCase("apple")){return new Apple();}else if(which.equalsIgnoreCase("grape")){return new Grape();}else if(which.equalsIgnoreCase("strawberry")){return new Strawberry();}else{return null;}}public static void main(String[] args) {FruitGardener.factory("apple").grow();FruitGardener.factory("grape").plant();FruitGardener.factory("strawberry").harvest();}}
public final static DateFormat getTimeInstance(); public final static DateFormat getTimeInstance(int style); public final static DateFormat getTimeInstance(int style,Locale aLocale); .....