工厂方法模式✅

工厂方法是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法将一个类的实例化延迟到其子类。

适配器模式(Adapter)包含以下主要角色:

抽象产品类:RAM 、CPU

具体产品类:PcRAM、MacRAM、 PcCPU、 MacCPU

抽象工厂类: ComputerAccessoriesFactory

具体工厂类:PcFactory、 MacFactory

一、实验要求

使使用工厂方法模式实现下面描述的功能:
“电脑配件生产工厂生产内存、CPU等硬件设备,这些内存、CPU的品牌、其型号并不一定相同。”

根据下面的“产品等级结构-产品族”示意图,使用抽象工厂模式实现电脑配件生产过程并绘制相应的类图,
并运用面向对象编程语言实现该模式。

二、代码✅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package abs;

public interface ComputerAccessoriesFactory {
CPU produceCPU();
RAM produceRAM();
}
public interface CPU {
void discribe();
}
public class MacCPU implements CPU {
public void discribe()
{
System.out.println("This is produce the MacCPU");
}
}
public class MacFactory implements ComputerAccessoriesFactory{

public MacCPU produceCPU() {
System.out.println("PC_CPU produced! >_<");
return new MacCPU();
}

public MacRAM produceRAM() {
System.out.println("PC_RAM produced! >_<");
return new MacRAM();
}
}
public class MacRAM implements RAM {
public void discribe() {
System.out.println("This is produce the MacRAM ");
}
}
public class PcCPU implements CPU
{
public void discribe()
{
System.out.println("This is produce the PC_CPU");
}
}
public class PcFactory implements ComputerAccessoriesFactory
{
public PcCPU produceCPU() {
System.out.println("PC_CPU produced! >_<");
return new PcCPU();
}

public PcRAM produceRAM() {
System.out.println("PC_RAM produced! >_<");
return new PcRAM();
}
}
public class PcRAM implements RAM
{
public void discribe() {
System.out.println("This is produce the PC_RAM ");
}
}
public interface RAM {
void discribe();
}
public class MacFactory implements ComputerAccessoriesFactory{

public MacCPU produceCPU() {
System.out.println("PC_CPU produced! >_<");
return new MacCPU();
}

public MacRAM produceRAM() {
System.out.println("PC_RAM produced! >_<");
return new MacRAM();
}
}

public class MainClass {
public static void main(String[] args) {
ComputerAccessoriesFactory a = new PcFactory();
ComputerAccessoriesFactory b = new MacFactory();
ComputerAccessoriesFactory c = new MacFactory();
ComputerAccessoriesFactory d = new PcFactory();
CPU cpu = a.produceCPU();
RAM ram = b.produceRAM();
CPU cpu1 = c.produceCPU();
RAM ram1 =d.produceRAM();
cpu.discribe();
ram.discribe();
cpu1.discribe();
ram1.discribe();
}
}

类图

适配器方法

代码结果

工厂方法

总结

这些都是基础的,不会的多多看前面文章.