//產品接口 public interface IProduct { void produce(); } //產品實現 public class Product implements IProduct{ @Override public void produce() { System.out.println("產品邏輯"); } } //產品工廠 public class ProductFactory { public static IProduct createProduct(String name) { Product product = null; if ("product".equals(name)) { product = new Product(); } return product; } }
public class Test { public static void main(String[] args) { IProduct product = ProductFactory.createProduct("product"); product.produce(); } }
產品邏輯
經過簡單工廠模式,能夠看到有三個要素html
public abstract class Video { public abstract void produce(); }
public class VideoFactory { /** * 每次新增長產品實線會修改代碼 * 不符合開閉原則 * @param type * @return */ public Video getVideo(String type) { if ("java".equalsIgnoreCase(type)) { return new JavaVideo(); } else if ("python".equalsIgnoreCase(type)) { return new PythonVideo(); } else return null; } /** * 反射方式實現 * @param clazz * @return */ public Video getVideo(Class clazz) { Video video = null; try { video = (Video) Class.forName(clazz.getName()).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return video; } }
public class JavaVideo extends Video { @Override public void produce() { System.out.println("錄製Java課程視頻"); } }
public class PythonVideo extends Video{ @Override public void produce() { System.out.println("錄製Python課程"); } }
public class Test { // public static void main(String[] args) { // Video video = new JavaVideo(); // video.produce(); // } public static void main(String[] args) { VideoFactory videoFactory = new VideoFactory(); Video video1 = videoFactory.getVideo("python"); if (video1 != null) { video1.produce(); } Video video2 = videoFactory.getVideo("java"); if (video2 != null) { video2.produce(); } } /* public static void main(String[] args) { VideoFactory videoFactory = new VideoFactory(); Video video = videoFactory.getVideo(PythonVideo.class); if (video != null) { video.produce(); } }*/ }
錄製Python課程 錄製Java課程視頻
//根據輸入參數區分的具體實現 if (aLocale.hasExtensions()) { String caltype = aLocale.getUnicodeLocaleType("ca"); if (caltype != null) { switch (caltype) { case "buddhist": cal = new BuddhistCalendar(zone, aLocale); break; case "japanese": cal = new JapaneseImperialCalendar(zone, aLocale); break; case "gregory": cal = new GregorianCalendar(zone, aLocale); break; } } }