(笔试题)编程题: 写一个Singleton出来???

java2times 2008-03-26 05:30:09
编程题: 写一个Singleton出来,最好带注释解释一下什么意思,谢谢各位大大
...全文
978 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zeng16107 2008-06-15
  • 打赏
  • 举报
回复
也问到过
ee4456 2008-03-26
  • 打赏
  • 举报
回复
JAVA设计模式,普遍的单例有3种...
gryes 2008-03-26
  • 打赏
  • 举报
回复
//饿汉式
public class EagerSingleton
{
//一上来就创建实例,所以叫饿汉
private static final EagerSingleton m_instance =
new EagerSingleton();
//private保证不能再被实例
private EagerSingleton() { }

public static EagerSingleton getInstance()
{
return m_instance;
}
}

//懒汉式
public class LazySingleton
{
private static LazySingleton
m_instance = null;
//private保证不能再被实例
private LazySingleton() { }

synchronized public static LazySingleton getInstance(){
//实例为空的时候才创建,否者直接拿来用,所以是懒汉
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}


构造方法是 private是单例模式关键
Johnson_Hong 2008-03-26
  • 打赏
  • 举报
回复

//饿汉式
public class EagerSingleton
{
//一上来就创建实例,所以叫饿汉
private static final EagerSingleton m_instance =
new EagerSingleton();

private EagerSingleton() { }

public static EagerSingleton getInstance()
{
return m_instance;
}
}

//懒汉式
public class LazySingleton
{
private static LazySingleton
m_instance = null;

private LazySingleton() { }

synchronized public static LazySingleton getInstance(){
//实例为空的时候才创建,否者直接拿来用,所以是懒汉
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}

Rhyme620 2008-03-26
  • 打赏
  • 举报
回复

public class SingleClass{
private static SingleClass instance;
protected SingleClass(){}

public static SingleClass GetInstance() {
if(instance == null)
{
instance = new SingleClass();
}
return instance;
}

}
lizhi1026 2008-03-26
  • 打赏
  • 举报
回复
单子模式singleton:
//类属性,类方法
private static SingleTonPattern stp;
//注意返回的是对象
public static SingleTonPattern getIntance(){
if(stp == null){
stp = new SingleTonPattern();
}
return stp;
在单子模式中只存在一个实例。很节约内存的。
zhangsw_good 2008-03-26
  • 打赏
  • 举报
回复
作用是一个类Class只有一个实例存在

public class Singleton {
private Singleton(){}
   // private只供内部调用
   private static Singleton instance = new Singleton();
   //供外部访问本 class 的静态方法,可以直接访问  
   public static Singleton getInstance() {
     return instance;   
   }
}
}
hjxaut 2008-03-26
  • 打赏
  • 举报
回复



try {
ServerSocket server = new ServerSocket(9000);
} catch (IOException e) {
// TODO 自动生成 catch 块
System.out.println("端口被占用!");
}


上述代码写错了,不好意思,呵呵
hjxaut 2008-03-26
  • 打赏
  • 举报
回复

try{
ServerPort port=new ServerPort(9000);}
catch(IOException e){
}


原理很简单,检查是否端口已经被占用。不过你也可以使用文件锁来实现。就是项目下建立一个空文件,在程序启动时获取该文件的锁
获取到则说明没有实例在运行,否则说明已经有实例运行

不知道答案是不是你要的。
ee4456 2008-03-26
  • 打赏
  • 举报
回复
写一个单例出来,就是写一个类,构造方法是私有的,不能该类外部new ,然后写一个静态方法,可以根据类型调用得到该类的唯一实例
healer_kx 2008-03-26
  • 打赏
  • 举报
回复
以前每年都要写好几次,再也不想写了。

62,630

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧