用Java反射优化工厂设计模式

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类型
	}
}

常见降低耦合方法:
利用多态:向上转型、接口回调
适配器模式:加一个中间类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值