Java Tip 30: Polymorphism and Java

3 篇文章 0 订阅

http://www.javaworld.com/javaworld/javatips/jw-javatip30.html

This article first looks at single polymorphism and, by iteratively extending and improving an example in Java, goes on to explore multiple polymorphism in greater detail. 

In my previous Java Tip, I discussed how you can get your compiler to check that constant values are valid. As I mentioned in that tip, although the use of these constructs makes code more readable, it can lead to a series of if/else if clauses in the client code. This new Java Tip also incorporates typesafe constants and a technique that can be used to remove the aforementioned condition checking.

Single polymorphism

Single polymorphism is achieved by method overriding. Listing 1 provides an example of single polymorphism, demonstrating how classes that implement the Traceable interface simply write their current state to System.out. Instances of Traceable can be registered with the TraceManager, which will invoke the Trace() method on each of these instances in TraceAll().

Listing 1: Single polymorphism


public interface Traceable
{
      public void Trace();
}
public class Foo implements Traceable
{
      public void toString()  {/* return state of object*/};
      public void Trace()
      {
            System.out.println( this ); 
      }
}
public class TraceManager
{
      public void Register( Traceable item ) {  }
      public void TraceAll() 
      {
            /* iterate all Traceable objects and invoke
            Trace()*/
      }
}


The code in Listing 1 works fine if you only want to trace your objects to System.out. However, if you then wanted to trace these objects to a logfile or via a socket, you're in trouble! A bad solution would be to define a set of interfaces, one for each type, as show in Listing 2.

Listing 2: Defining a set of interfaces


public interface  SystemTraceable { public void Trace();}
public interface LogFileTraceable { public void Trace();}
public interface SocketTracable { public void Trace();}


What's the problem with this approach? You have to implement a new interface each time your requirements change, resulting in a proliferation of interfaces and classes which can make a design difficult to understand and extend.

Multiple polymorphism

Multiple polymorphism is when an abstract class uses another abstract class. Listing 3 shows how multiple polymorphism solves the problem introduced in Listing 2. An OutputDevice abstraction has been introduced for traceable objects to write to. With this design, any traceable object can write to any OutputDevice.

Listing 3: Multiple polymorphism


public interface OutputDevice
{
      public void Write( String out );
}
public class SystemOutput implements OutputDevice
{
      public void Write( String out )
      {
            System.out.println( out );
      }
}
public class LogFileOutput implements OutputDevice {/* impl */ }
public interface Traceable
{
      public void Trace( OutputDevice device);
}
public class Foo implements Traceable
{
      public void toString()  {/* return state of object*/};
      public void Trace( OutputDevice device)
      {
            device.Write( toString ); 
      }
}
public class TraceManager
{
      public void Register( Traceable item ) {  }
      public void TraceAll( OutputDevice device) 
      {
            /* iterate all Traceable
            objects and invoke Trace( device )*/
      }
}


Using multiple polymorphism leads to a more scalable and extensible design. As new OutputDevice classes are identified and implemented, the TraceManager class remains unaltered -- as do the classes that implement Traceable.

Beyond multiple polymorphism

As illustrated and stated above, you can get designs that are more scalable and extensible with multiple polymorphism. But there is still one hurdle to overcome.

Say, for example, you now want to extend your design to allow different levels of tracing that can be altered at run time -- that is, you want to be able to specify to the TraceManager that objects should trace in "verbose" mode at one point during execution and in "minimal" mode at another. If runtime behavior changes are not required, you could consider subclassing Foo in Listing 1 to implement a "verbose" Trace(), "minimal" Trace(), and so on, and then register the appropriate subclass instances with TraceManager. As with the example in Listing 2, a proliferation of subclasses can lead to a design that is difficult to understand and extend. Listing 4 illustrates one approach to solving this problem.

Listing 4: Solving the design problem


public class Mode
{
      private Mode() {}
      public static final MINIMAL = new Mode();
      public static final VERBOSE = new Mode();
      //
}
//OutputDevice as in Listing 3.
public interface Traceable 
{
      public void Trace( OutputDevice device, Mode mode);
}
public class Foo implements Traceable
{
      private void MinimalTrace(OutputDevice device){/* write state to
device*/}
      private void VerboseTrace(OutputDevice device){/* write state to
device*/}
      public void Trace( OutputDevice device, Mode mode)
      {
            if(Mode.MINIMAL==mode)

MinimalTrace( device ); else if(Mode.VERBOSE==mode) VerboseTrace( device ); } } public class TraceManager { public void Register( Traceable item ) { } public void TraceAll( OutputDevice device, Mode mode) { /* iterate all Traceable objects and invoke Trace( device, mode ) */ } }


typesafe constant class has been added to the program to specify the current mode. TraceManager delegates the mode parameter along with the OutputDevice to the traceable objects. Foo now has to check the mode parameter to determine the appropriate level of tracing to perform.

This design works well, and it leads me neatly back to a question I addressed in my previous tip on type safe constants -- how can you eliminate the if/else if clause associated with enumerated parameters?

Those readers who have progressed from C to C++ and now to Java may be familiar with a technique that was used in C (before C++ became mainstream) to eliminate giant switch statements by mapping an enum to a pointer-to-function in a table. If you are not familiar with pointer syntax in C, don't worry: Listing 5 simply demonstrates a mapping from an enumerated type to a function.

Listing 5: Mapping from enumerated types to function pointers in C


void Func1() {}
void Func2() {}
//etc
enum{TYPE1,TYPE2,MAX};
void GiantSwitch( int type )
{
      switch( type )
      {
            case TYPE1  : Func1();break;
            case TYPE2  : Func2();break;
            //etc
      }
}
//would become
typedef void (*PFUNC)();
PFUNC funcTable[ MAX ];
void Init()
{
      funcTable[ TYPE1 ] = Func1();
      funcTable[ TYPE2 ] = Func2();
      //..etc
}
void NoSwitch( int type )
{
      //range check
      funcTable[ type ] ();
}


Those of you who have come to Java directly from C++ may be interested in experimenting with C structs with embeddedfuncTables to emulate C++ virtual functions.

Anyway, back to the plot!

As Java doesn't have functions or pointers to functions, we can't port the C code to Java. However, Listing 5 demonstrates a mapping from an enumerated type to a function, and Listing 6 shows you how to achieve the same effect in Java.

Listing 6: Improving the design



//everthing else the same as Listing 4. public class Foo implements Traceable { private Hashtable map = new Hashtable(); private class MinimalTrace implements Traceable {/* impl */} private class VerboseTrace implements Traceable {/* impl */} public Foo() { //initialize map map.put( Mode.MIMINAL, new MinimalTrace() ); map.put( Mode.VERBOSE, new VerboseTrace() ); } public void Trace( OutputDevice device, Mode mode) { Traceable t=(Traceable)map.get( mode ); t.Trace( device ); } }


Foo now has innerclasses that implement the different levels ofTrace() and uses a Hashtable to map the Mode to the implementation class. To improve the efficiency of the Trace() method, we can introduce a currentMode instance variable with an associatedcurrentImpl to avoid the overhead of the Hashtable.get() method, as shown in Listing 7.

Listing 7: Improving efficiency


public class Foo implements Traceable
{
      private Mode currentMode;
      private Traceable currentImpl;
      private Hashtable map = new Hashtable();
      private class MinimalTrace implements Traceable {/* impl */}
      private class VerboseTrace implements Traceable {/* impl */}
      public Foo()
      {
            //init map as Listing 6
            //assign currentMode and currentImpl to a default
      }
      public void Trace( OutputDevice device, Mode mode )
      {
            if(mode!=currentMode)
            {
                  currentMode=mode;
                  currentImpl=(Traceable)map.get( mode );
            }
            currentImpl.Trace( device );
      }
}


One final area of improvement would be to defer the instantiation of the implementation classes until the classes are required, a technique known as lazy instantiation. I will discuss lazy instantiation in depth in a future article, including how the implications and benefits for Java differ from those for C++.

I will leave it as an exercise for the reader to modify the design of Foo to incorporate lazy instantiation.

About the author

Philip Bishop is technical director and a consultant at Eveque Systems Ltd in the U.K. Eveque Systems specializes in the design and implementation of distributed object systems using Java, CORBA, C++, ODBMS, and so on.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值