2013-11-20 55 views
0

请考虑以下情况。我想要根据或class C从这里拨打电话的位置获得methoddA()methoddA()的不同行为。如何实现这一点,重写方法在这里不起作用。构图覆盖方法

class A 
{ 
    public methodA(){ //some code } 
} 

class B 
{ 
    A a = new A() 
    public methodB() 
    { 
     a.methodA(); 
    } 
} 

class C 
{ 
    B b = new B(); 

    public methodC() 
    { 
     b.methodB(); 
    } 
} 

class D 
{ 
    B b = new B(); 

    public methodD() 
    { 
     b.methodB(); 
    } 
} 
+0

你想实现什么样的不同行为? –

+0

可能是一些不同的代码,如果从类C中调用,并且从类D调用一些不同的代码。 – eatSleepCode

+0

为什么要这样?如果你想要不同的行为取决于函数的调用,也许你可以调用不同的方法? – user902383

回答

0

这里你需要的是多态性。首先创建一个接口 -

public interface MyInterface 
{ 
    void methodA(); 
} 

然后创建两个不同的实现了两个不同的行为 -

public class First implements MyInterface 
{ 
    public void methodA() { 
     // first behavior 
    } 
} 

public class Second implements MyInterface 
{ 
    public void methodA() { 
     // second behavior 
    } 
} 

现在创建您的其他类如下 -

class B 
{ 
    public void methodB(MyInterface m) 
    { 
     m.methodA(); 
    } 
} 

class C 
{ 
    B b = new B(); 

    public void methodC() 
    { 
     // Pass the corresponding behavior implementation 
     // as argument here. 
     b.methodB(new First()); 
    } 
} 

class D 
{ 
    B b = new B(); 

    public void methodD() 
    { 
     // Pass the second behavior implementation. 
     b.methodB(new Second()); 
    } 
} 

这将导致更多可维护的代码。

0

您可以通过类名来你的方法作为一个字符串,并以你的方法检查

if(className.equals("A") // or use isInstanceOf() if you are passing objects of A/B 
//do something 

if(className.equals("B") 
// do something else. 

为什么你需要两种不同的实现? 这个简单的把戏可以为你工作......请纠正我,如果我错了......

0

我下面的代码我修改了类A1和类B1的方法签名接受对象和类似的同时从类调用方法C和D类,无论我们称之为B1类方法,都将此作为参考。在A1类中,我们可以检查instanceof对象并确定调用类。

class A1 
{ 
    public void methodA(Object c){ //some code } 
     if (D.class.isInstance(c)){ 
      System.out.println("Called from Class D"); 
     }else if (C.class.isInstance(c)){ 
      System.out.println("Called from Class c"); 
     }else{ 
      System.out.println("Called from Some diff class"); 
     } 
    } 

} 

class B1 
{ 
    A1 a = new A1(); 
    public void methodB(Object c) 
    { 
     a.methodA(c); 
    } 
} 

class C 
{ 
    B1 b = new B1(); 

    public void methodC() 
    { 
     b.methodB(this); 
    } 
} 

class D 
{ 
    B1 b = new B1(); 

    public void methodD() 
    { 
     b.methodB(this); 
    } 
} 


public class Testnew{ 
    public static void main(String args[]){ 
     D d = new D(); 
     d.methodD(); 

     C c = new C(); 
     c.methodC(); 

     B1 b = new B1(); 
     b.methodB(b); 
    } 
} 
+0

以这种方式使用'instanceof'几乎总是会产生代码异味。有更好的设计方案。 –