关于工厂模式的性能问题

_星星之火_ 2017-11-25 07:09:53
工厂方法模式:分几个组成部分:

1:定义一个电脑抽象类:Compute

[java] view plain copy
public abstract class Compute {
//定义作为电脑的公共方法
public void playMedia(){
System.out.println("I can play some media")
}
//定义标签,每个品牌的电脑型号品牌不同所以需要定义成抽象类
public abstract void brand(String a);

}
2:定义一个子类实现Compute抽象类
[java] view plain copy
public class Lenovo extends Compute{
@Override
public void brand(String b) {
System.out.println("My brand is " + b);
}
}
3:定义一个工厂抽象类:
[java] view plain copy
public abstract class Builder {
public abstract Compute buildeCompute(Class<? extends Compute> c);
}
4:定义一个工厂类的实现
[java] view plain copy
public class ConcreteBuilder extends Builder {
@Override
public Compute builderCompute(Class<? extends Compute> c) {
Compute compute = null;
try {
compute = (Compute)Class.forName(c.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return compute;
}
}
public class Client {
public static void main(String[] args){
/*
* 利用工厂方法生产一些电脑耗费的时间
* */
List<Compute> ca = new ArrayList<>();
long start = System.currentTimeMillis();
Builder b = new ConcreteBuilder();
for(int i = 0;i < 100000;i++){
Compute a = b.builderCompute(Lenovo.class);
ca.add(a);
}
long end = System.currentTimeMillis();
int takeTime = (int)(end - start);
System.out.println("It's take " + takeTime);
/*
* 利用普通的方法进行新建对象所耗费的时间
*
* */
//清除列表
ca.clear();
long start1 = System.currentTimeMillis();
for(int i = 0;i< 100000;i++){
Compute a = new Lenovo();
ca.add(a);
}
long end1 = System.currentTimeMillis();
System.out.println("It's take " + (end1 - start1));




}
}
运行结果:
It's take 92
It's take 4
Process finished with exit code 0
虽然设计模式很好但是性能很差怎么破呢?
...全文
201 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
conquer0715 2017-11-26
  • 打赏
  • 举报
回复
实际应用中这点性能损失是完全可以接受的,你整个系统都性能评价往往在于数据库、网络连接,不恰当的算法等代码处,另外,设计模式更加关注的是代码的可理解性,可修改性等代码规范!

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧