定义:抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,无须指定它们具体的类。
类型:创建型。
横着来看,海尔洗衣机、海尔冰箱、海尔空调,它们都是海尔品牌,它们都属于海尔这个产品族。
竖着来看,海尔空调、美的空调、海信空调,它们都是空调,它们属于同一个产品等级结构。
工厂方法模式针对的就是产品等级结构,抽象工厂模式针对的就是产品族。
如下图所示,当一个工厂可以创建出分属于不同产品等级结构的一个产品族中的所有对象时,使用抽象工厂模式更为简单高效。
CourseFactory.java
package com.czh.creational.abstractfactory;
public interface CourseFactory {
Video getVideo();
Note getNote();
}
JavaCourseFactory.java
package com.czh.creational.abstractfactory;
public class JavaCourseFactory implements CourseFactory {
@Override
public Video getVideo() {
return new JavaVideo();
}
@Override
public Note getNote() {
return new JavaNote();
}
}
PythonCourseFactory.java
package com.czh.creational.abstractfactory;
public class PythonCourseFactory implements CourseFactory {
@Override
public Video getVideo() {
return new PythonVideo();
}
@Override
public Note getNote() {
return new PythonNote();
}
}
Video.java
package com.czh.creational.abstractfactory;
public abstract class Video {
public abstract void play();
}
JavaVideo.java
package com.czh.creational.abstractfactory;
public class JavaVideo extends Video {
@Override
public void play() {
System.out.println("播放Java课程视频");
}
}
PythonVideo.java
package com.czh.creational.abstractfactory;
public class PythonVideo extends Video {
@Override
public void play() {
System.out.println("播放Python课程视频");
}
}
Note.java
package com.czh.creational.abstractfactory;
public abstract class Note {
public abstract void read();
}
JavaNote.java
package com.czh.creational.abstractfactory;
public class JavaNote extends Note {
@Override
public void read() {
System.out.println("阅读Java课程笔记");
}
}
PythonNote.java
package com.czh.creational.abstractfactory;
public class PythonNote extends Note {
@Override
public void read() {
System.out.println("阅读Python课程笔记");
}
}
Test.java
package com.czh.creational.abstractfactory;
public class Test {
public static void main(String[] args) {
CourseFactory courseFactory1 = new JavaCourseFactory();
Video video1 = courseFactory1.getVideo();
Note note1 = courseFactory1.getNote();
video1.play();
note1.read();
CourseFactory courseFactory2 = new PythonCourseFactory();
Video video2 = courseFactory2.getVideo();
Note note2 = courseFactory2.getNote();
video2.play();
note2.read();
}
}