您的位置:首页 > 其它

设计模式-简单工厂模式(Simple Factory)

2013-07-07 00:00 267 查看
分为:一个抽象类(或接口)、实现抽象类、工厂类

Product.java

1
package
cn.foxeye.design.simple.factory;
2

3

public

interface
Product {
4

5

void
operation();
6

7
}
8


Product1.java

1
package
cn.foxeye.design.simple.factory;
2

3

public

class
Product1
implements
Product {
4

5
@Override
6

public

void
operation() {
7
System.out.println(
"
产品1执行操作
"
);
8
}
9

10
}
11


Product2.java

1
package
cn.foxeye.design.simple.factory;
2

3

public

class
Product2
implements
Product {
4

5
@Override
6

public

void
operation() {
7
System.out.println(
"
产品2执行操作
"
);
8
}
9

10
}
11


ProductFactory.java

1
package
cn.foxeye.design.simple.factory;
2

3

public

class
ProductFactory {
4

5

public

static
Product createProduct(String productName) {
6

if
(
"
1
"
.equals(productName)) {
7

return

new
Product1();
8
}
else

if
(
"
2
"
.equals(productName)) {
9

return

new
Product2();
10
}
11

12

return

null
;
13

14
}
15

16
}
17


Main.java

1
package
cn.foxeye.design.simple.factory;
2

3

public

class
Main {
4

5

public

static

void
main(String[] args) {
6
Product product1
=
ProductFactory.createProduct(
"
1
"
);
7
product1.operation();
8
Product product2
=
ProductFactory.createProduct(
"
2
"
);
9
product2.operation();
10
}
11

12
}
13
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐