设计模式
来源:互联网 发布:mac做win8启动盘 编辑:程序博客网 时间:2024/05/21 04:22
设计模式(二)
1、单例模式
单例模式提供了一种创建对象和获取对象的方法,该方法使得类内部创建一次该实例,使用该实例时不需要再次创建(一般也不能再次创建)。
1、创建该类,构造方法设为private(其他类就调用不到该构造方法)
public class Animal { private String name; private static Animal instance = new Animal(); private Animal() { name = "动物"; } public static Animal getInstance() { return instance; } public void showName(){ System.out.println(name); }}
2、测试
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Animal animal = Animal.getInstance(); animal.showName(); }}
3、输出(控制台输出)
动物
2、享元模式
享元模式的思想是尽可能复用已创建的对象,避免创建新对象。
1、创建接口
public interface Biology { public void show();}
2、创建Animal类,Animal具有名字和表演方法
public class Animal implements Biology{ private String name; public void show() { // TODO Auto-generated method stub System.out.println("轮到"+name+"表演啦!!"); } public Animal(String name){ this.name=name; }}
3、创建Zoo,Zoo有笼子,并且会购买Animal并且让它们表演,当要表演的动物笼子里没有时,就需要去市场购买。
public class Zoo { //笼子,动物园所有动物都在这里 public static final Map<String , Animal> animals =new HashMap(); public void show(String str){ Animal animal = (Animal) animals.get(str); if(animal == null){ animal = new Animal(str); System.out.println("动物园没有"+str+",快去买!!!"); //将新买的动物放进笼子里 animals.put(str, animal); } animal.show(); }}
4、测试(随机让各种Animal参加表演,看Zoo是否每次都创建Animal)
public class Main { public static void main(String[] args) { String[] animals={"狮子","老虎","大象","熊猫","长颈鹿"}; Zoo zoo = new Zoo(); for(int i=0;i<20;i++){ String ShowingAnimal = animals[(int) (Math.random()*animals.length)]; zoo.show(ShowingAnimal); } }}
5、结果(控制台输出)
动物园没有熊猫,快去买!!!轮到熊猫表演啦!!动物园没有狮子,快去买!!!轮到狮子表演啦!!轮到熊猫表演啦!!动物园没有老虎,快去买!!!轮到老虎表演啦!!轮到老虎表演啦!!动物园没有长颈鹿,快去买!!!轮到长颈鹿表演啦!!轮到老虎表演啦!!轮到熊猫表演啦!!轮到狮子表演啦!!轮到老虎表演啦!!轮到狮子表演啦!!轮到长颈鹿表演啦!!轮到狮子表演啦!!轮到长颈鹿表演啦!!轮到老虎表演啦!!轮到老虎表演啦!!动物园没有大象,快去买!!!轮到大象表演啦!!轮到狮子表演啦!!轮到熊猫表演啦!!轮到长颈鹿表演啦!!
结论:
享元模式可以尽可能的节省创建对象所花费的资源。
阅读全文
1 0
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式~~~~~~~~~~
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- android.support.v4.app.Fragment和android.app.Fragment区别
- 【mysql】配置MySQL,解决安装过程中的问题
- SVN的安装与常用功能使用以及解决安装配置过程中的一些错误
- 最大最小公倍数
- Linux Shell脚本基础(二)
- 设计模式
- Java字符串过滤回车和换行符
- 排列组合
- CIFS文件系统
- 启发式算法给Gurobi 输入初始解
- java 常用集合list与Set、Map区别及适用场景总结
- widerface转换为pascal数据集的格式
- 概率论学习
- POJ 2135 Farm Tour(最小费用最大流)