本文实例讲述了java设计模式之工厂模式。分享给大家供大家参考,具体如下:
工厂模式(factory)
涉及到4个角色:抽象工厂类角色,具体工厂类角色,抽象产品类角色和具体产品类角色。
抽象工厂类角色使用接口或者父类来描述工厂的行为,
具体工厂类角色负责创建某一类型的产品对象。
抽象产品类可以使用接口或者父类来描述产品对象的行为特征。
具体产品类就是某一具体的对象。
工厂模式在工厂类也实现了多态,而不仅仅是在产品对象上实现多态。
它可以应对不同类型的产品对应一种具体的工厂。
其设计模式如下:
抽象工厂类 IFactory
?
|
1
2
3
4
5
6
7
8
9
|
package org.test.design.f;
/**
*
* @author lushuaiyin
*
*/
public interface IFactory {
IProduct createProduct();
}
|
具体工厂类 CarFactory ComputerFactory
?
|
1
2
3
4
5
6
|
package org.test.design.f;
public class CarFactory implements IFactory {
public IProduct createProduct() {
return new Car();
}
}
|
?
|
1
2
3
4
5
6
|
package org.test.design.f;
public class ComputerFactory implements IFactory {
public IProduct createProduct() {
return new Computer();
}
}
|
抽象产品类 IProduct
?
|
1
2
3
4
|
package org.test.design.f;
public interface IProduct {
void work();
}
|
具体产品类 Car Computer
?
|
1
2
3
4
5
6
|
package org.test.design.f;
public class Car implements IProduct{
public void work() {
System.out.println("I am car.");
}
}
|
?
|
1
2
3
4
5
6
|
package org.test.design.f;
public class Computer implements IProduct{
public void work() {
System.out.println("I am Computer.");
}
}
|
测试:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package org.test.design.f;
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
IFactory carFactory=new CarFactory();
IProduct car=(IProduct)carFactory.createProduct();
car.work();
IFactory pcFactory=new ComputerFactory();
IProduct pc=(IProduct)pcFactory.createProduct();
pc.work();
}
}
/*打印
I am car.
I am Computer.
*/
|
希望本文所述对大家java程序设计有所帮助。
原文链接:http://blog.csdn.net/lushuaiyin/article/details/8917363
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 58
-
Xshell实现Windows上传文件到Linux主机的方法
2025-05-25 66 -
php array_walk array_map array_filter区别案例详解
2025-05-29 24 -
2025-05-27 52
-
2025-05-25 72
热门评论


