本次实例以掷骰子的例子展开。
1. 类图
2. Java实现代码
package cn.edu.ynu.sei.multiton;
/**
* 使用骰子的客户
*
* @author 88250
* @version 1.0.0, 2007-8-19
*/
public class Client
{
private static Die die1, die2;
/**
* 程序入口点
* @param args 应该为<code>null</code>
*/
public static void main(String[] args)
{
die1 = Die.getInstance(1);
die2 = Die.getInstance(2);
System.out.println(die1.dice());
System.out.println(die2.dice());
}
}
/**
* 使用骰子的客户
*
* @author 88250
* @version 1.0.0, 2007-8-19
*/
public class Client
{
private static Die die1, die2;
/**
* 程序入口点
* @param args 应该为<code>null</code>
*/
public static void main(String[] args)
{
die1 = Die.getInstance(1);
die2 = Die.getInstance(2);
System.out.println(die1.dice());
System.out.println(die2.dice());
}
}
package cn.edu.ynu.sei.multiton;
import java.util.Date;
import java.util.Random;
/**
* 骰子,应用多例模式实现
*
* @author 88250
* @version 1.0.0, 2007-8-19
*/
public class Die
{
private static Die die1 = new Die();
private static Die die2 = new Die();
/**
* 私有的构造器,保证外部无法直接实例化该类
*/
private Die(){};
/**
* 工厂方法
* @param whichOne 骰子编号
* @return
*/
public static Die getInstance(int whichOne)
{
if (whichOne == 1)
{
return die1;
}
else
{
return die2;
}
}
/**
* 掷骰子,返回一个在1~6之间的随机数
* @return
*/
public synchronized int dice()
{
Date d = new Date();
Random r = new Random(d.getTime());
int value = r.nextInt();
value = Math.abs(value);
value = value % 6;
value += 1;
return value;
}
}
import java.util.Date;
import java.util.Random;
/**
* 骰子,应用多例模式实现
*
* @author 88250
* @version 1.0.0, 2007-8-19
*/
public class Die
{
private static Die die1 = new Die();
private static Die die2 = new Die();
/**
* 私有的构造器,保证外部无法直接实例化该类
*/
private Die(){};
/**
* 工厂方法
* @param whichOne 骰子编号
* @return
*/
public static Die getInstance(int whichOne)
{
if (whichOne == 1)
{
return die1;
}
else
{
return die2;
}
}
/**
* 掷骰子,返回一个在1~6之间的随机数
* @return
*/
public synchronized int dice()
{
Date d = new Date();
Random r = new Random(d.getTime());
int value = r.nextInt();
value = Math.abs(value);
value = value % 6;
value += 1;
return value;
}
}