用Java反射优化工厂设计模式
程序员文章站
2022-03-09 20:29:32
...
1.正常工厂模式
interface AA {
public abstract void f1();
}
class BB implements AA {
@Override
public void f1() {
System.out.println("this is class BB");
}
}
class CC implements AA {
@Override
public void f1() {
System.out.println("this is class CC");
}
}
class Factory {
public static AA getInstance(String str) {
if (str.equals("a")) {
return new BB();
} else if (str.equals("b")) {
return new CC();
}
return null;
}
}
public class TestDemo3 {
public static void main(String args[]) {
AA a = Factory.getInstance("a");
a.f1();
}
}
输出:
this is class BB
2.降低耦合度的工厂设计模式(反射)
package t1;
interface AA {
public abstract void f1();
}
class BB implements AA {
@Override
public void f1() {
System.out.println("this is class BB");
}
}
class CC implements AA {
@Override
public void f1() {
System.out.println("this is class CC");
}
}
class Factory {
public static AA getInstance(String className) {
Object object = null;
try {
object = Class.forName(className).newInstance();//jdk8后变成@deprecated
//object = Class.forName(className).getDeclaredConstructor().newInstance();//jdk8后建议用这个
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AA a = (AA) object;
return a;
}
}
public class TestDemo2 {
public static void main(String args[]) {
AA a = Factory.getInstance("t1.BB");
a.f1();
}
}
/**
Class.newInstance()的@deprecated源码说明,换为Constructor中newInstance
* @deprecated This method propagates any exception thrown by the
* nullary constructor, including a checked exception. Use of
* this method effectively bypasses the compile-time exception
* checking that would otherwise be performed by the compiler.
* The {@link
* java.lang.reflect.Constructor#newInstance(java.lang.Object...)
* Constructor.newInstance} method avoids this problem by wrapping
* any exception thrown by the constructor in a (checked) {@link
* java.lang.reflect.InvocationTargetException}.
*/
输出
this is class BB
3.反射好处:
1)可扩展性提升:使用反射机制后每次增加新类,不需要修改getInstance()函数。
2)耦合度降低:new实例化对象时,明确指定类的构造方法,所以new是造成耦合的最大元凶,解决代码耦合问题,首先就要解决new实例化对象的操作。
3)为什么用返射降低了耦合:
普通工厂getInstance():return new BB(); 与class BB有直接关系
反射工厂:不返回实例,耦合度降低
4.耦合:两个类间的紧密程度
class A {
public void f1() {
\\NOP
}
}
class B {
public f2(A a) {
a.f1();
}
}
public class TestDemo {
public static void main(String args[]) {
B b = new B();
b.f2(new A()); //class A 与 class B强耦合,B中f2()参数必须为classA类型
}
}
常见降低耦合方法:
利用多态:向上转型、接口回调
适配器模式:加一个中间类
上一篇: 设计模式-简单工厂模式+反射机制