你是否看过JAVA核心技术,里面讲到类的继承里面的“上塑造型”。你可以这样写
class a
{
    void a()
    {
        
     }
}class a1 extends a
{
     void a()
     {
       ....
      }
}
class a2 extends a
{
     void a()
     {
       ...
      }
}a b1 = new a1();
a b2 = new a2();这就是“上塑造型”,b1.a()和b2.a()的结果你可以看到他们是被重载以后的方法,而不是
a中的方法,我想这个大概是你要达到的效果.如果你知道更详细的话,可以看看我提到的那本书,里面讲的很清楚

解决方案 »

  1.   

    public static void main(String[] args) {
        Instrument5 instr;    intstr=new Wind5();
        //或instr=new Percussion5();  这样你执行方法
        intstr.play()就会动态绑定到Wind5的实现上去。这个还不能算是一个模式吧,只是多态的一个例子。
      

  2.   

    //: Shapes.java
    // Polymorphism in Javaclass Shape { 
      void draw() {}
      void erase() {} 
    }class Circle extends Shape {
      void draw() { 
        System.out.println("Circle.draw()"); 
      }
      void erase() { 
        System.out.println("Circle.erase()"); 
      }
    }class Square extends Shape {
      void draw() { 
        System.out.println("Square.draw()"); 
      }
      void erase() { 
        System.out.println("Square.erase()"); 
      }
    }class Triangle extends Shape {
      void draw() { 
        System.out.println("Triangle.draw()"); 
      }
      void erase() { 
        System.out.println("Triangle.erase()");
      }
    }public class Shapes {
      public static Shape randShape() {
        switch((int)(Math.random() * 3)) {
          default: // To quiet the compiler
          case 0: return new Circle();
          case 1: return new Square();
          case 2: return new Triangle();
        }
      }
      public static void main(String[] args) {
        Shape[] s = new Shape[9];
        // Fill up the array with shapes:
        for(int i = 0; i < s.length; i++)
          s[i] = randShape();
        // Make polymorphic method calls:
        for(int i = 0; i < s.length; i++)
          s[i].draw();
      }
    } ///:~
    看来是这个了,看看对不?
      

  3.   

    Shape[] s = new Shape[9];
    s[i].draw();
    以上两行,看来你已经理解了上塑的含义
      

  4.   

    楼主请看你的这段代码:
    <<
        switch((int)(Math.random() * 3)) {
          default: // To quiet the compiler
          case 0: return new Circle();
          case 1: return new Square();
          case 2: return new Triangle();
        }
    >>
    这段代码是否不好?如果我们需要增加新的Shape比如Pentangle,你的修改是否很大?
      

  5.   

    我觉得 kypfos(政治面貌:一世清白) 的比较好,楼主是想通过条件调用不同的不同类的方法,这是面向对象的一个原则。
    public static void main(String[] args) {
        Instrument5 instr;
        //这一段怎么写,让instr或是wind5或是Percussion5;
        /*
          根据你的条件 new 不同的类,比如: instr = new wind5();
        */
        instr.play  //可能是 Wind5 也可能是Percussion5,就是上边的怎么样让instr通过一缎程序,知道他到底执行那个方法??????    
      }
      

  6.   

    其实这个地方用多态来解决是很显而易见的。问题实际上转换为如何可以动态地选择不同的实现类实例上面来了,在这个地方如何做到可以遵循OCP。
      

  7.   

    开闭原则,"敏捷软件开发"同"Java与模式"中都有讲解。