关于工厂模式的性能问题
工厂方法模式:分几个组成部分:
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
虽然设计模式很好但是性能很差怎么破呢?