class A {public
public void T1 () {
}
public void T2 () {
}
}
// Class B wants to have both: t1 (), t2 () , t3 (), t4 (), t5 (), t6 () functions
// better compared to class B design approach: instead of object composition inherits the priority
public class B the extends a {
public void T3 () {
}
public void T4 () {
}
}
public class B2 {
// combination 1 - save memory, slower
public void T1 () {
; new new A () T1 ().
}
public void T2 () {
; new new A () T2 ().
}
public void T3 () {
}
public void T4 ( ) {
}
// combination 2 - c life cycle length (size memory occupancy time), but faster
private C c = new C () ;
public void t5(){
c.t5();
}
public void t6(){
c.t6();
}
}
public class C {
public void t5(){
}
public void t6(){
}
}
public interface Api {
public void t1();
}
public class Impl1 implements Api{
@Override
public void t1() {
System.out.println("1111111111111111");
}
}
public class Impl2 implements Api{
@Override
public void t1() {
System.out.println("2222222222222");
}
}
public class Client {
public static void main(String[] args) throws Exception {
Class c=Class.forName("cn.hncu.design.two.Impl2");
Api api=(Api) c.newInstance();
api.t1();
}
}
//同时与模块Client1,Client2交互的通用接口,,,这种设计不好,建议采用分成两个专用接口来做
public interface Api {
//模块Client1访问的方法
public abstract void t1();
public abstract void t2();
//模块Client2访问的方法
public abstract void t3();
public abstract void t4();
}
//与Client1模块交互的专用接口
public interface Api1 {
public abstract void t1();
public abstract void t2();
}
//与Client2模块交互的专用接口
public interface Api2 {
public abstract void t3();
public abstract void t4();
}
public class Client1 {
public static void main(String[] args) {
Api api = null;// 实现项目中,这里用类反射或工厂类创建出一个实现类对象
api.t1();
api.t2();
api.t3();
api.t4();
// 专用接口的调用方式
Api1 aapi = null;
aapi.t1();
aapi.t2();
Api2 aapi2 = null;
aapi2.t3();
aapi2.t4();
}
}
public class B {
/*
public void t(A a){
System.out.println( a.t1() );
}
*/
//在依赖不是很严重的地方,可以考虑剪断依赖链---自己实现依赖对方获得的功能
public String t1(){
return "111111111";
}
}
public class A {
public String t1(){
return "1111111111111";
}
}
public class B {
/*
public void t(A a){
System.out.println( a.t1() );
}
*/
//在依赖不是很严重的地方,可以考虑剪断依赖链---自己实现依赖对方获得的功能
public String t1(){
return "111111111";
}
}