简单工厂模式(Simple Factory)

文章目录

  • 定义与类型
  • 适用场景
  • 优点
  • 缺点
  • 简单工厂代码示例
  • 使用反射演进简单工厂

定义与类型

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

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

适用场景

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

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

优点

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

缺点

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

简单工厂代码示例

简单工厂模式(Simple Factory)_第1张图片

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();
    }
}

你可能感兴趣的:(设计模式(Java),设计模式,简单工厂模式,Java)