文档库

最新最全的文档下载
当前位置:文档库 > 5.抽象工厂模式-单例模式答案

5.抽象工厂模式-单例模式答案

(4) 抽象工厂模式

电脑配件生产工厂生产内存、CPU等硬件设备,这些内存、CPU的品牌、型号并不一定相同,根据下面的“产品等级结构-产品族”示意图,使用抽象工厂模式实现电脑配件生产过程并绘制相应的类图,绘制类图并编程实现。

5.抽象工厂模式-单例模式答案

5.抽象工厂模式-单例模式答案

interface CPU

{

void discribe();

}

interface RAM

{

void discribe();

}

class PcCPU implements CPU

{

public void discribe()

{

System.out.println("PcCPU");

}

}

class MacCPU implements CPU

{

public void discribe()

{

System.out.println("MacCPU");

}

}

class PcRAM implements RAM

{

public void discribe()

{

System.out.println("PcRAM");

}

}

class MacRAM implements RAM

{

public void discribe()

{

System.out.println("MacRAM");

}

}

interface ComputerPartsFactory

{

CPU produceCPU();

RAM produceRAM();

}

class PcFactory implements ComputerPartsFactory

{

public PcCPU produceCPU() {

System.out.println("PcCPU produced!");

return new PcCPU();

}

public PcRAM produceRAM() {

System.out.println("PcRAM produced!");

return new PcRAM();

}

}

class MacFactory implements ComputerPartsFactory

{

public MacCPU produceCPU() {

System.out.println("MacCPU produced!");

return new MacCPU();

}

public MacRAM produceRAM() {

System.out.println("MacRAM produced!");

return new MacRAM();

}

}

class ComputerPartsClient

{

public static void main(String a[])

{

ComputerPartsFactory factory;

CPU cpu;

RAM ram;

factory=(ComputerPartsFactory)XMLUtil.getBean();//Pc OR Mac

cpu=factory.produceCPU();

cpu.discribe();

ram=factory.produceRAM();

ram.discribe();

}

}

(6) 单例模式

用懒汉式单例实现在某系统运行时,其登录界面类LoginForm只能够弹出一个,如果第二次实例化该类则提示“程序已运行”。绘制类图并编程实现。

5.抽象工厂模式-单例模式答案

class LoginForm extends JFrame{ //Java.swing包中的JFrame类用于创建窗口

private static LoginForm uniqueInstance=null;

private LoginForm()

{

//设置标题

this.setTitle("LoginForm");

this.setSize(400, 300); //setSize(int width, int height)

//设置关闭按钮的事件

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

//设置是否可见

this.setVisible(true);

}

public static LoginForm getInstance()

{

if(uniqueInstance==null)

{

uniqueInstance=new LoginForm();

}else{

JOptionPane.showMessageDialog(null, "LoginFrame已经在运行!");

}

return uniqueInstance;

}

}

class LoginFormClient

{

public static void main(String a[])

{

LoginForm s1=null,s2=null;

s1=LoginForm.getInstance();

s2=LoginForm.getInstance();

System.out.println("s1==s2?");

System.out.println(s1==s2);

}

}

运行结果:

5.抽象工厂模式-单例模式答案

5.抽象工厂模式-单例模式答案