1.静态调用函数
package com;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton s = Singleton.getInstance();
s.setSeed(5);
// System.out.println(s.toString());
for(int i=0;i<5;i++)
{
// Singleton s2 = Singleton.getInstance();
System.out.println("The Random number is :"+(Math.abs(s.nextInt())));
}
}
}
2.单例模式类
package com;
import java.util.Random;
public class Singleton {
private Random generator;
private static Singleton instance;
private Singleton() {
super();
// TODO Auto-generated constructor stub
generator = new Random();
}
public void setSeed(int seed)
{
generator.setSeed( seed);
}
public float nextInt()
{
return generator.nextFloat();
// generator
}
public static synchronized Singleton getInstance()
{
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
}
3.总结:
(1)声明单例模式用一个静态实例,并复写一个静态获取实例的方法
private static Singleton instance;
public static synchronized Singleton getInstance()
{
}
(2)单例模式使得应用程序在运行时保持只能有一个实例,在一些大的应用程序中,主程序只需要有一个,因此需要使用单例模式。
阅读(1779) | 评论(0) | 转发(0) |