手写一个简单工厂模式
产品接口:
package com.ajax.pattern.simplefactory; public interface Fruit { void desc(); }
产品1:
package com.ajax.pattern.simplefactory; public class Apple implements Fruit { @Override public void desc() { System.out.println("苹果"); } }
产品2:
package com.ajax.pattern.simplefactory; public class Orange implements Fruit { @Override public void desc() { System.out.println("橙子"); } }
工厂:
package com.ajax.pattern.simplefactory; public class SimpleFactory { public static Fruit getFruit(String name) { switch (name) { case "apple": return new Apple(); case "orange": return new Orange(); default: return null; } } }
运行:
package com.ajax.pattern.simplefactory; public class Run { public static void main(String[] args) { SimpleFactory.getFruit("apple").desc(); } }
原文地址:https://www.cnblogs.com/caizhiqin/p/11269159.html
时间: 2024-10-02 20:57:18