簡單工廠(Simple Factory)模式java
簡單點講.就是實例化的過程(也就是new一個對象)咱們交給工廠去解決,咱們只需告訴工廠咱們須要什麼app
public interface Fruit { String NAME_APPLE = "apple"; String NAME_BANNANA = "banana"; void getName(); }
public class Apple implements Fruit{ @Override public void getName() { System.out.println("我是蘋果"); } }
public class Banana implements Fruit{ @Override public void getName() { System.out.println("我是香蕉"); } }
public class Factory { public static Fruit getFruit(String fruitName){ if(fruitName.equals(Fruit.NAME_APPLE)){ return new Apple(); }else if(fruitName.equals(Fruit.NAME_BANNANA)){ return new Banana(); } return null; } }
public class Demo { public static void main(String[] args) { Fruit fruit = Factory.getFruit(Fruit.NAME_APPLE); fruit.getName(); } }
控制檯console:ide
我是蘋果ui