工厂设计模式
来源:互联网 发布:python png alpha合成 编辑:程序博客网 时间:2024/06/07 14:36
普通工的厂设计模式
interface Fruit{ public void eat();}class Apple implements Fruit{ public void eat() { System.out.println("eat apple"); }}class Oranage implements Fruit{ public void eat() { System.out.println("eat orange"); }}class Factory{ public static Fruit getFruit() { Fruit fruit=null; fruit= new Apple(); return fruit; }}public class Test{ public static void main(String args[]) { Apple apple=(Apple)Factory.getFruit(); apple.eat(); }}
这里的工厂设计模式的缺点是:如果要取得orange类的实例,则还要修改工厂类。此时可以利用反射的机制进行完善。代码如下:
package com.xing.hang;interface Fruit{ public void eat();}class Apple implements Fruit{ public void eat() { System.out.println("eat apple"); }}class Orange implements Fruit{ public void eat() { System.out.println("eat orange"); }}class Factory{ public static Fruit getFruit(String str) throws Exception { Fruit fruit=null; fruit= (Fruit)Class.forName(str).newInstance(); return fruit; }}public class Test{ public static void main(String args[]) throws Exception { Apple apple=(Apple)Factory.getFruit("com.xing.hang.Apple"); Orange orange=(Orange)Factory.getFruit("com.xing.hang.Orange"); apple.eat(); orange.eat(); }}
0 0
- 设计模式--工厂设计
- 设计模式------工厂模式
- 设计模式------工厂模式
- 设计模式 [ 工厂模式 ]
- 设计模式--工厂模式
- 设计模式-工厂模式
- 设计模式--工厂模式
- 设计模式 工厂模式
- 设计模式-工厂模式
- 设计模式 -- 工厂模式
- 设计模式-工厂模式
- 设计模式----工厂模式
- 设计模式---工厂模式
- 设计模式-工厂模式
- 设计模式--工厂模式
- 设计模式---工厂模式
- 设计模式-工厂模式
- 设计模式--工厂模式
- HDU 4908 BestCoder Sequence——BestCoder Round #3
- exec调用新程序
- Cube Stacking
- JavaScript数字字符转数据类型
- introduction to Java Programming 编程题5.3<回文整数>
- 工厂设计模式
- 键盘录入一个数组并进行排序
- 在win7系统下使用TortoiseGit(乌龟git)简单操作Git@OSC
- 网页添加百度地图缩略图
- 懒得笔记6 spring hibernate template
- 提交java性能的注意点
- Java学习--(九)异常处理
- android截图
- hdu5391Zball in Tina Town