
欢迎阅读这个由 3 部分组成的指南。在这篇文章中,我将提供设计模式的基本介绍以及示例。
这篇具体文章将介绍什么是设计模式、为什么我们应该了解它们、设计模式的类型和结构模式。
快速链接:
创作模式结构模式行为模式
什么是设计模式?
立即学习“Java免费学习笔记(深入)”;
设计模式是软件开发中常见问题的经过验证的解决方案。它们帮助开发人员以结构化的方式解决复杂的任务,并允许他们重用成功的解决方案,使他们的代码更易于理解和维护。将设计模式视为解决构建软件时出现的典型问题的蓝图。
为什么我们应该了解它们?
了解设计模式可以帮助开发人员以结构化且高效的方式解决常见问题,使代码更具可重用性、可维护性和可扩展性。
想象一下餐厅的厨房。厨师按照食谱(设计模式)准备菜肴。厨师没有每次都重新发明流程,而是使用经过验证的步骤来始终如一地提供相同质量的菜肴。同样,设计模式可以帮助开发人员高效地解决问题,而无需每次都重新发明解决方案。
设计模式类型:
在 java 中,设计模式分为三大类:
1。创建模式:这些模式有助于以灵活且可重用的方式创建对象。
2.结构模式:这些模式重点关注对象如何排列和连接以形成更大的系统。
3.行为模式: 这些模式处理对象如何相互交互和通信。
比格设计
比格设计是135编辑器旗下一款一站式、多场景、智能化的在线图片编辑器
124 查看详情
结构模式
结构模式关注如何组织和连接对象以形成更大、更复杂的系统。
适配器:
如果您在新应用程序中使用旧的数据库api,您可以使用适配器模式使旧的api能够在新系统中工作。
interface newdatabase { void fetchdata();}class olddatabase { public void getdata() { system.out.println("fetching data from old database"); }}class olddatabaseadapter implements newdatabase { private olddatabase olddatabase; public olddatabaseadapter(olddatabase olddatabase) { this.olddatabase = olddatabase; } public void fetchdata() { olddatabase.getdata(); }}
桥:
您有一个可以绘制不同形状的绘图应用程序。桥接模式可以让你将形状(抽象)与绘图实现(实现)分开。
interface drawingapi { void drawcircle(double x, double y, double radius);}class circle { private double x, y, radius; private drawingapi drawingapi; public circle(double x, double y, double radius, drawingapi drawingapi) { this.x = x; this.y = y; this.radius = radius; this.drawingapi = drawingapi; } public void draw() { drawingapi.drawcircle(x, y, radius); }}
复合:
在文件系统中,文件夹可以包含文件和其他文件夹。复合模式允许您以相同的方式处理文件和文件夹。
interface filesystemcomponent { void showdetails();}class file implements filesystemcomponent { private string name; public file(string name) { this.name = name; } public void showdetails() { system.out.println("file: " + name); }}class folder implements filesystemcomponent { private list components = new arraylist(); public void add(filesystemcomponent component) { components.add(component); } public void showdetails() { for (filesystemcomponent component : components) { component.showdetails(); } }}
装饰器:
您想要向 car 类添加新功能而不修改原始 car。装饰器模式可让您动态添加天窗或皮革座椅等功能。
interface Car { void assemble();}class BasicCar implements Car { public void assemble() { System.out.println("Basic car assembled."); }}class CarDecorator implements Car { protected Car car; public CarDecorator(Car car) { this.car = car; } public void assemble() { this.car.assemble(); }}class SunroofDecorator extends CarDecorator { public SunroofDecorator(Car car) { super(car); } public void assemble() { super.assemble(); System.out.println("Adding sunroof."); }}
以上就是Java 中的设计模式 – 简化指南 #2的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/367061.html
微信扫一扫
支付宝扫一扫