设计模式(简单工厂模式)
来源:互联网 发布:wish数据分析 编辑:程序博客网 时间:2024/05/23 19:17
工厂模式是我们在开发过程中比较常用的一种设计模式, 相对来说也是比较简单的, 主要的核心思想就是工厂创建对象, 不需要我们去一个一个的new出来对象, 这样的好处就是进一步的封装了代码, 不会将我们的对象暴漏给客户端, 从而使我们的代码来说相对比较安全.
其中主要用到的方法和类主要有(以经典的图形举例):
图形有正方形, 长方形, 三角形, 圆 . 我们用简单的两种图形做举例.
工厂模式的创建应用了面向对象的多态属性, 我们需要首先创建一个Shape接口,来对外提供公共的接口
public interface Shape { void draw();}
创建两个图形类Rectangle 和 Square 分别实现Shape接口:
Square 类
public class Square implements Shape { @Override public void draw() { System.out.println("这是Square类的方法"); }}
Rectangle 类
public class Rectangle implements Shape { @Override public void draw() { System.out.println("这是Rectangle 类的方法"); } //类自己的方法 public void draw1() { System.out.println("这是Rectangle 类的draw1方法"); }}
现在所有的零件都齐全了, 就缺少一个工厂来把他们组装到一起了
添加 ShapeFactory 工厂类(这是工厂模式的核心)
public class ShapeFactory { public Shape getShape (String type){ if (type == null){ return null; } //创建Square if (type.equalsIgnoreCase("Square")){ return new Square(); } //创建Rectangle if (type.equalsIgnoreCase("Rectangle")){ return new Rectangle(); } return null; }}
写一个Main方法来测试:
public class TestMain { public static void main(String[] args){ ShapeFactory shapeFactory = new ShapeFactory(); Shape square = shapeFactory.getShape("Square"); square.draw(); Shape rectangle = shapeFactory.getShape("Rectangle"); rectangle.draw(); //调用类自己的方法 ,向下转型就好了 Rectangle rectangle1 = (Rectangle) shapeFactory.getShape("Rectangle"); rectangle1.draw1(); }}
输出
这是Square类的方法这是Rectangle 类的方法这是Rectangle 类的draw1方法
参考 :
https://www.w3cschool.cn/java/java-factory-pattern.html
阅读全文
0 0
- 简单工厂设计模式
- 设计模式-----简单工厂
- 简单工厂设计模式
- 设计模式:简单工厂
- 设计模式 - 简单工厂
- 设计模式 简单工厂
- 【设计模式】【简单工厂】
- 简单工厂设计模式
- 简单工厂设计模式
- 设计模式--简单工厂
- 简单工厂设计模式
- 简单工厂设计模式
- 设计模式------------简单工厂
- 设计模式--简单工厂
- 简单工厂设计模式
- 设计模式---------简单工厂
- 设计模式--简单工厂
- 简单工厂设计模式
- oj 给你一个整数列表L, 输出L的中位数(若结果为小数,则保留一位小数)。
- shell学习整理(3)- 玩转变量和环境变量
- centos 7 安装oracle11r前置
- ZooKeeper笔记
- gensim中文处理
- 设计模式(简单工厂模式)
- 9月21日云栖精选夜读:专访新浪微博黄波:千人千面_机器学习赋能用户信息流消费
- Web
- 使用JavaMail通过SMTP协议发送局域网(内网)邮件
- Unity技巧总结03 转美术数字动态设置
- Submit string: submit:trigger=0,bugtype=2,modulename=
- Linux 乱码问题
- LazyMan题目讲解
- vs2015在Debug模式下运行出现"应用程序无法正常启动(0x000007b)"的错误解决方法