1.定义
创建对象的工作由工厂完成。
2.优点
屏蔽对象创建的复杂过程,让用户直接使用对象。
3.代码示例
public abstract class Video {
abstract void produce();
}
public class JavaVideo extends Video {
@Override
void produce() {
System.out.println("录制Java视频");
}
}
public class PythonVideo extends Video{
@Override
void produce() {
System.out.println("录制Python视频");
}
}
public abstract class VideoFactory {
abstract Video getVideo() ;
}
public class JavaVideoFactory extends VideoFactory{
@Override
Video getVideo() {
return new JavaVideo();
}
}
public class PythonVideoFactory extends VideoFactory{
@Override
Video getVideo() {
return new PythonVideo();
}
}
public class Test {
public static void main(String[] args) {
VideoFactory videoFactory = new JavaVideoFactory();
Video video = videoFactory.getVideo();
video.produce();
}
}
4.源码解析
public interface Collection<E> extends Iterable<E> {
Iterator<E> iterator();
}
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
......
}
}