潜在类型机制

潜在类型机制是一种代码组织和复用机制,当用某个实例调用方法时,它只要求实现该实例实现了这些方法子集,而不用继承或实现某个接口,换句话说,程序不关心你什么类型,只要你的类型带有这些方法就行了,这样满足你可以横跨类继承结构,而调用不属于某个公共接口的方法,
代码例子:
Python的实现

class Dog:
    def speak(self);
        print "Arf!"
    def sit(self):
        print "Sitting"
    def reproudce(self):
        pass
class Robot:
    def speak(self):
        print "Click!"
    def sit(selt)
        print "Clank!"
    def oilChange(self)
        pass
def perform(anything):
    anything.speak()
    anything.sit()
a=Dog()
b=Robot()
perform(a)
perform(b

c++的实现

class Dog {
public:
  void speak() {}
  void sit() {}
  void reproduce() {}
};
class Robot {
public:
  void speak() {}
  void sit() {}
  void oilChange() {
};
template<class T> void perform(T anything) {
  anything.speak();
  anything.sit();
}
int main() {
  Dog d;
  Robot r;
  perform(d);
  perform(r);
} 

java的实现:

class Mime {
      public void walkAgainstTheWind() {}
      public void sit() { System.out.println("Pretending to sit"); }
      public void speak() { System.out.println("gensture"); }
      public void pushInvisibleWalls() {}
      public String toString() { return "Mime"; }
    }
    class SmartDog {
      public void speak() { System.out.println("Woof!"); }
      public void sit() { System.out.println("Sitting"); }
      public void reproduce() {}
    }   
    class CommunicateReflectively {
      public static void perform(Object speaker) {
        Class<?> spkr = speaker.getClass();
        try {
          try {
            Method speak = spkr.getMethod("speak");
            speak.invoke(speaker);
          } catch(NoSuchMethodException e) {
              System.out.println(speaker + " cannot speak");
          }
          try {
            Method sit = spkr.getMethod("sit");
            sit.invoke(speaker);
          } catch(NoSuchMethodException e) {
              System.out.println(speaker + " cannot sit");
          }
        } catch(Exception e) {
          throw new RuntimeException(speaker.toString(), e);
        }
      }
    }
    public class LatentReflection {
      public static void main(String[] args) {
        CommunicateReflectively.perform(new SmartDog());
        CommunicateReflectively.perform(new Mime());
      }
    } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值