DBMNG数据库管理与应用

科学是实事求是的学问,来不得半点虚假。
当前位置:首页 > 经验分享 > Java开发

Java中单态设计模式

此博文是转自新浪博客中一名叫做”俊俊的BLOG“用户的一篇博文。感觉此博文确实很不错,所以在此拿出来分享一下!(笔者只是对其所举的代码略做了一些修改)

一概念:

设计模式:设计模式是指经过大量的实践总结和理论化之后的优选的代码结构、编程风格、以及解决问题的思路。

单态设计模式:采取一定的方法保证在整个软件系统中,对某个类只能产生一个对象实例,并且该类只提供一个取得其对象的实例方法。

二实现:

java中实现单态模式只需要执行以下三步:

1.将构造函数声明为private。这样就只能在该类的内部生成对象,而不能在外部通过new来产生对象。

2.在类内部生成一个静态的实例。

3.提供一个静态的方法用于外部取得该类的实例。

三举例:

class Chinese {

static Chinese chinese = new Chinese();

private Chinese(){

}

public static Chinese getInstance() {

return chinese;

}

}

改进:

class Chinese {

static Chinese chinese = null;

private Chinese() {

}

public static Chinese getInstance() {

if (chinese == null) {

chinese = new Chinese();

}

return chinese;

}

}

这是网上找来的资料;

下面是自己编写的程序代码:

package mypkg ;

class Single {

static Single ref = null;        //= new Single();//因为要保证静态函数getInstance()能调用该变量ref,所以必需设置成static。

private Single(){                 //设置成private的目的是防止外部调用生成其它对象    

System.out.println(“hao”);

}

public static Single getInstance(){//为了使外面的函数生产Single对象,只有通过此函数才能生产,所以它必需是public和static

if(ref == null){

ref = new Single();

}

return ref;

}

}

class Other {

public static int i = 0;

public Other() {

System.out.println(“Form i=” + (++i));

}

public static Other getOther() {

return (new Other());

}

}

public class testSingle {

public static int i = 0;

public static void main(String[] args) {

Single obj1 = Single.getInstance();

Single obj2 = Single.getInstance();

Single obj3 = Single.getInstance();

Other ob1 = Other.getOther();

Other ob2 = Other.getOther();

System.out.println((obj1 == obj2) && (obj2 == obj3) && (obj1 == obj3));

System.out.println(“******/n” + (ob1 == ob2));

}

}

其执行结果是:

hao
Form i=1
Form i=2
true
******

false

可以看出,单态设计模式中只生产一个对象,obj1、obj2、obj3都是同一个对象,故结果中只输出一次 hao。而非单态模式可以生产很多的对象,如ob1和ob2就是2个不同的对象。

http://liuxiaowei199001.blog.163.com/blog/static/193805325201182343020758/

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号