Java设计模式学习之抽象工厂模式
抽象工厂模式是创造型模式的一种,他和工厂模式类似,可以看作是工厂的工厂
工厂模式中使用一堆 if-else结构来返回客户端要的子类实例。抽象工厂模式不是用if-else,而是使用不同子类的工厂代理来返回子类实例
下面例子对之前工厂模式进行适当的修改,增加生成PC的PCFactory, 生成Server的ServerFactory
,以及修改ComputerFactory
PCFactory.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.walterlife.dp.FactoryDP;
public class PCFactory implements ComputerAbstractFactory {
private String ram;
private String hdd;
private String cpu;
public PCFactory(String ram, String hdd, String cpu) {
this.ram = ram;
this.hdd = hdd;
this.cpu = cpu;
}
@Override
public Computer createComputer() {
return new PC(ram, hdd, cpu);
}
}
ServerFactory.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.walterlife.dp.FactoryDP;
public class ServerFactory implements ComputerAbstractFactory {
private String ram;
private String hdd;
private String cpu;
public ServerFactory(String ram, String hdd, String cpu) {
this.ram = ram;
this.hdd = hdd;
this.cpu = cpu;
}
@Override
public Computer createComputer() {
return new Server(ram, hdd, cpu);
}
}
ComputerAbstractFactory.java1
2
3
4
5package com.walterlife.dp.FactoryDP;
public interface ComputerAbstractFactory {
public Computer createComputer();
}
ComputerFactory.java1
2
3
4
5
6
7
8
9
10
11package com.walterlife.dp.FactoryDP;
import org.apache.log4j.Logger;
public class ComputerFactory {
static Logger logger = Logger.getLogger(ComputerFactory.class);
public static Computer getComputer(ComputerAbstractFactory factory) {
return factory.createComputer();
}
}
测试抽象工厂代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void testFactoryDP() {
Computer pc = ComputerFactory.getComputer(new PCFactory("2GB", "500GB",
"2.4 GHz"));
Computer server = ComputerFactory.getComputer(new ServerFactory("16GB", "1TB", "4 GHz"));
if(pc != null) {
logger.info("PC config :" + pc.toString());
} else {
logger.warn("PC instace is null!!!");
}
if(server != null) {
logger.info("Server config :" + server.toString());
} else {
logger.warn("Server instace is null!!!");
}
}
运行结果1
22015-08-23 18:14:06 INFO com.walterlife.dp.App testFactoryDP:26 -> PC config :RAM: 2.GB HDD: 500GB CPU: 2.4 GHz
2015-08-23 18:14:06 INFO com.walterlife.dp.App testFactoryDP:32 -> Server config :RAM: 16GB HDD: 1TB CPU: 4 GHz