Skip to content

抽象工厂模式是一种创建型设计模式, 它能创建一系列相关的对象, 而无需指定其具体类。

业务场景:在线教育网站,课程模块,一个课程由视频和文章共同组成,我们需要寻找java课程和Python课程

新建视频和文章抽象类

java
public abstract class Video {
    public abstract void produce();
}
public abstract class Article {
    public abstract void produce();
}

新建Java视频和文章实现类

java
public class JavaVideo extends Video {
    @Override
    public void produce() {
        System.out.println("java视频");
    }
}
public class JavaArticle extends Article {
    @Override
    public void produce() {
        System.out.println("java文章");
    }
}

新建Python视频和文章实现类

java
public class PythonVideo extends Video {
    @Override
    public void produce() {
        System.out.println("Python视频");
    }
}
public class PythonArticle extends Article {
    @Override
    public void produce() {
        System.out.println("Python文章");
    }
}

新建超级工厂接口

java
public interface CourseFactory {
    Video getVideo();
    Article getArticle();
}

java超级工厂实现类

java
public class JavaCourseFactory implements CourseFactory{
    @Override
    public Video getVideo() {
        return new JavaVideo();
    }

    @Override
    public Article getArticle() {
        return new JavaArticle();
    }
}

Python超级工厂实现类

java
public class PythonCourseFactory implements CourseFactory{
    @Override
    public Video getVideo() {
        return new PythonVideo();
    }

    @Override
    public Article getArticle() {
        return new PythonArticle();
    }
}

使用

java
@Test
public void test02(){
    CourseFactory courseFactory = new JavaCourseFactory();
    Article article = courseFactory.getArticle();
    Video video = courseFactory.getVideo();
    article.produce();
    video.produce();
}