Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Definition and Code demonstration of simple Factory pattern in java Design pattern

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

这篇文章主要讲解了"java设计模式中简单工厂模式的定义及代码演示",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"java设计模式中简单工厂模式的定义及代码演示"吧!

1、简单工厂定义由一个工厂对象决定创建哪一种产品类的实例,不属于GOF23种设计模式。适用场景1) 工厂类负责创建的对象比较少2) 客户端(应用层)只知道传入工厂类的参创建对象(逻辑)不关心优点:只需要传入一个正确的参数,就可以获取你所需要的对象而无需知道其创建细节。缺点:工厂类的职责相对过重,增加新的产品,需要修改工厂类的判断逻辑,违背开闭原则。2、代码演示public abstract class Video { public abstract void produce();}public class JavaVideo extends Video { @Override public void produce() { System.out.println("录制Java课程视频"); }}public class PythonVideo extends Video { @Override public void produce() { System.out.println("录制Python课程视频"); }}public class VideoFactory { public Video getVideo(Class c){ Video video = null; try { video = (Video) Class.forName(c.getName()).newInstance(); } catch (Exception e) { e.printStackTrace(); } return video; } public Video getVideo(String type){ if("java".equalsIgnoreCase(type)){ return new JavaVideo(); }else if("python".equalsIgnoreCase(type)){ return new PythonVideo(); } return null; }}public class Test { public static void main(String[] args) { VideoFactory videoFactory = new VideoFactory(); Video video = videoFactory.getVideo("java"); if(video == null){ return; } video.produce(); videoFactory = new VideoFactory(); video = videoFactory.getVideo(JavaVideo.class); if(video == null){ return; } video.produce(); }}感谢各位的阅读,以上就是"java设计模式中简单工厂模式的定义及代码演示"的内容了,经过本文的学习后,相信大家对java设计模式中简单工厂模式的定义及代码演示这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report