//工廠接口 public interface IFactory { IProduct createProduct(); } //產品接口 public interface IProduct { void produce(); } //工廠實現 public class Factory implements IFactory { @Override public IProduct createProduct() { return new Product(); } } //產品實現 public class Product implements IProduct{ @Override public void produce() { System.out.println("具體產品業務。"); } } //應用 / 測試類 public class Test { public static void main(String[] args) { IFactory factory = new Factory(); IProduct product = factory.createProduct(); product.produce(); } }
具體產品業務。
經過工廠方法模式的類圖能夠看到,工廠方法模式有四個要素:html
總結的說前端
//視頻工廠 public abstract class VideoFactory { public abstract Video getVideo(); } //視頻類 public abstract class Video { public abstract void produce(); }
//Java視頻工廠 public class JavaVideoFactory extends VideoFactory { @Override public JavaVideo getVideo() { return new JavaVideo(); } } //Java視頻 public class JavaVideo extends Video { @Override public void produce() { System.out.println("錄製Java課程視頻"); } }
//Python視頻工廠 public class PythonVideoFactory extends VideoFactory { @Override public PythonVideo getVideo() { return new PythonVideo(); } } //Python視頻 public class PythonVideo extends Video{ @Override public void produce() { System.out.println("錄製Python課程"); } }
//前端視頻實現 public class FEVideoFactory extends VideoFactory { @Override public FEVideo getVideo() { return new FEVideo(); } } //前端視頻 public class FEVideo extends Video { @Override public void produce() { System.out.println("錄製前端視頻"); } }
public class Test { public static void main(String[] args) { VideoFactory videoFactory = new JavaVideoFactory(); Video video1 = videoFactory.getVideo(); video1.produce(); videoFactory = new PythonVideoFactory(); Video video2 = videoFactory.getVideo(); video2.produce(); videoFactory = new FEVideoFactory(); Video video3 = videoFactory.getVideo(); video3.produce(); } }
錄製Java課程視頻 錄製Python課程 錄製前端視頻
Collection.iterator()方法java
public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { //省略了具體實現 }
工廠方法模式
:https://github.com/sigmako/design-pattern/tree/master/factory-methodgit
慕課網設計模式精講
: https://coding.imooc.com/class/270.html 23種設計模式(2):工廠方法模式
: https://blog.csdn.net/zhengzhb/article/details/7348707