工厂模式【创建模式第二篇】
工厂模式的几种形态:
1、简单工厂模式,又叫做静态工厂方法(Static Factory Method)模式。
2、工厂方法模式,又称为多态性工厂(Polymorphic Factory)模式
3、抽象工厂模式,又称工具(Kit或ToolKit)模式
简单工厂模式(Simple Factory)
1、模式:
简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式。
它是由一个工厂对象决定创建出哪一种产品类的实例。
2、举例://水果接口public interface Fruit{void grow();//生长void harvest();//收获void plant();//种植}//苹果类public class Apple implements Fruit{private int treeAge//树龄public void grow(){log("Apple is growing...");}public void harvest(){log("Apple has been harvented.");}public void plant(){log("Apple has been planted.");}//辅助方法public static void log(String msg){System.out.println(msg);}public int getTreeAge(){return treeAge;}public void setTreeAge(int treeAge){this.treeAge = treeAge;}}//葡萄类public class Grape implements Fruit{private boolean seedless;public void grow(){log("Grape is growing...");}public void harvest(){log("Grape has been harvested.");}public void plant(){log("Grape has been planted.");}public static void log(String msg){System.out.println(msg);}//有无籽方法public boolean getSeedless(){return seedless;}public void setSeedlees(boolean seedless){this.seedless = seedless;}}//草莓类public class Strawberry implements Fruit{public void grow(){log("Strawberry is growing...");}public void harvest(){log("Strawberry has been harvested.");}public void plant(){log("Strawberry has been planted.");}public static void log(String msg){System.out.println(msg);}}//农场园丁类,由他决定创建哪种水果类的实例public class FruitGardener{//静态工厂方法public static Fruit factory(String which) throws BadFruitException{if(which.equalslgnoreCase("apple")){return new Apple();}else if(which.equalslgnoreCase("grape")){return new Grape();}else if(which.equalslgnoreCase("strawberry")){return new Strawberry();}else{throw new BadFruitException("Bad fruit request");}}}//异常类public class BadFruitException extends Exception{public BadFruitException(String msg){super(msg);}}//测试类public class Test{FruitGardener gardener =new FruitGardener();try{gardener.factory("grape");gardener.factory("apple");gardener.factory("strawberry");gardener.factory("banana");//抛出异常}catch(BadFruitException e){System.out.println("dont't has this fruit.");}}