简单工厂模式(Simple Factory)

2023-12-26 00:57:59

定义与类型

定义:由一个工厂对象决定创建出哪一种产品类的实例

类型:创建型,但不属于GOF23种设计模式

适用场景

  • 工厂类负责创建的对象比较少

  • 客户端(应用层)只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心

优点

只需要传入一个正确的参数,就可以获取你所需要的对象,而无须知道其创建细节

缺点

工厂类的职责相对过重,增加新的产品时,需要修改工厂类的判断逻辑,违背开闭原则

简单工厂代码示例

在这里插入图片描述

Video.java

package com.czh.creational.simplefactory;

public abstract class Video {
    public abstract void play();
}

JavaVideo.java

package com.czh.creational.simplefactory;

public class JavaVideo extends Video {
    @Override
    public void play() {
        System.out.println("播放Java视频");
    }
}

PythonVideo.java

package com.czh.creational.simplefactory;

public class PythonVideo extends Video {
    @Override
    public void play() {
        System.out.println("播放Python视频");
    }
}

VideoFactory.java

package com.czh.creational.simplefactory;

public class VideoFactory {
    public Video getVideo(String type) {
        if ("java".equalsIgnoreCase(type)) {
            return new JavaVideo();
        } else if ("python".equalsIgnoreCase(type)) {
            return new PythonVideo();
        }
        return null;
    }
}

Test.java

package com.czh.creational.simplefactory;

public class Test {
    public static void main(String[] args) {
        VideoFactory videoFactory = new VideoFactory();
        Video video = videoFactory.getVideo("java");
        if (video == null) {
            return;
        }
        video.play();
    }
}

使用反射演进简单工厂

Video.java

package com.czh.creational.simplefactory;

public abstract class Video {
    public abstract void play();
}

JavaVideo.java

package com.czh.creational.simplefactory;

public class JavaVideo extends Video {
    @Override
    public void play() {
        System.out.println("播放Java视频");
    }
}

PythonVideo.java

package com.czh.creational.simplefactory;

public class PythonVideo extends Video {
    @Override
    public void play() {
        System.out.println("播放Python视频");
    }
}

VideoFactory.java

package com.czh.creational.simplefactory;

public class VideoFactory {
    public Video getVideo(Class c) {
        Video video = null;
        try {
            video = (Video) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return video;
    }
}

Test.java

package com.czh.creational.simplefactory;

public class Test {
    public static void main(String[] args) {
        VideoFactory videoFactory = new VideoFactory();
        Video video = videoFactory.getVideo(JavaVideo.class);
        if (video == null) {
            return;
        }
        video.play();
    }
}

文章来源:https://blog.csdn.net/qq_42815188/article/details/135170165
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。