何为简单工厂模式?
由一个工厂类根据传入的参数,动态创建并返回相应的具体的实例!
三个构成元素:
1、工厂类
2、抽象产品
3、具体产品
优点:
1、提高扩展性
2、隐藏具体的实现类,并不需要知道产品具体的创建过程,只需要向工厂类传入相应参数,就可以获取相应的产品实例!
代码演示:
|
// 抽象产品
package com.test.simplefactory;
public interface Person {
public String sayHello(String name);
public String sayGoodbye(String name);
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.test.simplefactory;
// 具体产品1
public class Chinese implements Person {
@Override
public String sayHello(String name) {
return "你好," + name;
}
@Override
public String sayGoodbye(String name) {
return "再见," + name;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.test.simplefactory;
// 具体产品2
public class American implements Person {
@Override
public String sayHello(String name) {
return "hello," + name;
}
@Override
public String sayGoodbye(String name) {
return "goodbye," + name;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package com.test.simplefactory;
// 工厂类
public class PersonFactory {
// 根据参数的不同返回不同的实例
public Person getPerson(String name){
Person person = null;
if("chinese".equals(name)){
person = new Chinese();
}else if("american".equals(name)){
person = new American();
}
return person;
}
}
|
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
|
package com.test.simplefactory;
// 测试
public class Client {
public static void main(String[] args) {
/*Person chinese = new Chinese();
System.out.println(chinese.sayHello("张三"));
System.out.println(chinese.sayGoodbye("张三"));
Person american = new American();
System.out.println(american.sayHello("Tom"));
System.out.println(american.sayGoodbye("Tom"));*/
PersonFactory factory = new PersonFactory();
Person chinese = factory.getPerson("chinese");
System.out.println(chinese.sayHello("张三"));
}
}
|