工厂方法
Posted linbq1911
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂方法相关的知识,希望对你有一定的参考价值。
1.定义:定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类,工厂方法让类的实例化推迟到子类中进行
2.类型:创建型
3.适用场景:创建对象需要大量重复的代码,客户端(应用层)不依赖于产品类的实例如何被创建、实现等细节,
一个类通过其子类来指定创建哪个对象
4.优点:用户只需要关心所需产品对应的工厂,无须关心创建细节;加入新产品符合开闭原则,提高可扩展性
5.缺点:类的个数容易过多,增加复杂度;增加了系统的抽象性和理解难度
6.实例目录package
7.实例UML类图
8.代码
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public abstract class Video { 4 public abstract void produce(); 5 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class JavaVideo extends Video { 4 public void produce() { 5 System.out.println("录制Java课程视频"); 6 } 7 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class PythonVideo extends Video { 4 public void produce() { 5 System.out.println("录制Python课程视频"); 6 } 7 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class FEVideo extends Video { 4 @Override 5 public void produce() { 6 System.out.println("录制FE课程视频"); 7 } 8 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public abstract class VideoFactory { 4 5 public abstract Video getVideo(); 6 /*public Video getVideo(String type){ 7 if("java".equalsIgnoreCase(type)){ 8 return new JavaVideo(); 9 }else if("python".equalsIgnoreCase(type)){ 10 return new PythonVideo(); 11 } 12 return null; 13 }*/ 14 15 /*public Video getVideo(Class clazz){ 16 Video video = null; 17 try{ 18 video = (Video) Class.forName(clazz.getName()).newInstance(); 19 }catch(InstantiationException e){ 20 e.printStackTrace(); 21 }catch(IllegalAccessException e){ 22 e.printStackTrace(); 23 }catch(ClassNotFoundException e){ 24 e.printStackTrace(); 25 } 26 return video; 27 }*/ 28 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class JavaVideoFactory extends VideoFactory { 4 @Override 5 public Video getVideo() { 6 return new JavaVideo(); 7 } 8 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class PythonVideoFactory extends VideoFactory { 4 @Override 5 public Video getVideo() { 6 return new PythonVideo(); 7 } 8 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class FEVideo extends Video { 4 @Override 5 public void produce() { 6 System.out.println("录制FE课程视频"); 7 } 8 }
1 package com.geely.design.pattern.creational.factorymethod; 2 3 public class Test { 4 public static void main(String[] args) { 5 6 VideoFactory videoFactory = new JavaVideoFactory(); 7 Video video = videoFactory.getVideo(); 8 video.produce(); 9 VideoFactory videoFactory2 = new PythonVideoFactory(); 10 Video video2 = videoFactory2.getVideo(); 11 video2.produce(); 12 VideoFactory videoFactory3 = new FEVideoFactory(); 13 Video video3 = videoFactory3.getVideo(); 14 video3.produce(); 15 } 16 }
以上是关于工厂方法的主要内容,如果未能解决你的问题,请参考以下文章