23种设计模式...
来源:互联网 发布:阿里云邮箱怎么登陆 编辑:程序博客网 时间:2024/06/05 19:01
23种设计模式,为了解决某一问题最行之有效的方法
单例设计模式.
想要保证对象唯一
1,为了避免其他程序过多的建立该类对象,先禁止其他程序建立对象.
2,还为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象.
3.为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式.
这三部怎么用代码体现呢?
1,将构造函数私有化.
2,在类中创建一个本类对象.
3提供一个方法可以获取该类的对象.
举例:
class Single{private Single(){} //私有话构造函数,将无法创建对象.private static Single si=new Single();//内部创建对象.public static Single getInstance(){return si; //提供一个方法返回这个对象,达到单例设计模式.}privateint num;public void setNum(int num){ this.num=num;}public int getNum(){return num;}}class SingleDemo{public static void main(String[] args){Single si1=Single.getInstance();Single si2=Single.getInstance();si1.setNum(234);System.out.println(si2.getNum());}}
模版设计模式
在定义功能时,功能的一部分是确定的,但是有一部分是不确定的.而确定的部分在使用不确定的部分.
那么这时就将不确定的部分暴露出去,由该类的子类去完成.
例:需求 获取一段程序的运行时间.
原理:获取程序开始和结束时间并相减即可.
获取时间:System.currentTimeMillis();
abstract class GetTime{public final void getTime(){long start=System.currentTimeMillis(); runCode(); //模版设计模式将需要改写的内容暴露出去long end=System.currentTimeMillis();System.out.println("运行时间:"+(end-start));}public abstract void runCode();}class SubTime extends GetTime{public void runCode(){ //子类改写抽象方法runCode();for(int x=0;x<4000;x++){System.out.print(x);}}}class Demo{public static void main(String[] args){GetTime ti=new SubTime();ti.getTime();}}
0 0
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- C#设计模式(23种设计模式)
- 23种设计模式-设计模式总结
- C#设计模式(23种设计模式)
- 【设计模式】:23种设计模式
- 【设计模式】23种设计模式
- 设计模式:23种设计模式综述
- C#设计模式(23种设计模式)
- 【设计模式】转载23种设计模式
- 设计模式分类,23种设计模式
- JAVA设计模式---23种设计模式
- 23种设计模式
- 23种模式设计
- 使用visual studio 2.13 编写wxWidgets程序
- Ajax全接触
- MDT ADK AIK
- 模式识别和机器学习、数据挖掘的区别与联系
- Could not load file or assembly system.data.sqlite.dll or one for it's depedencies
- 23种设计模式...
- protobuf-c学习小结
- linux opencv 2.4
- LeetCode 55/45 Jump Game I/II-----Greedy**
- LUA5.2中文函数名支持
- leetcode-195 Tenth Line
- Linux常用软件
- 奉献一个实用的JS动画弹出层效果
- MySQL主从复制与读写分离