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