潜在类型机制
Java不支持潜在类型泛化编程 但是可以利用接口、反射、适配器模拟
pyhton 支持潜在类型机制
class Dog:
def speak(self):
print("Dog")
def sit(self):
print("sitting")
def reproduce(self):
pass
class Robot:
def speak(self):
print("Click!")
def sit(self):
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);
return 0;
}
JAVA 通过反射模拟
package 潜在类型机制;
import java.lang.reflect.Method;
interface Isit{
public void sit();
}
class Mime implements Isit{
public void walkSgainstTheWind(){}
public void sit(){
System.out.println("Pretending Sitting!");
}
public void pushInvisibleWalls(){}
public String toString(){
return "Mine";
}
}
class SmartDog implements Isit {
public void speak(){
System.out.println("Woof!");
}
public void sit(){
System.out.println("SmartDog Sitting!");
}
public void reproduce(){}
}
class CommunicateReflectively {
public static void preform(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 speak = spkr.getMethod("sit");
speak.invoke(speaker);
} catch (NoSuchMethodException e) {
System.out.println(speaker + " cannot sit");
}
}catch (Exception e){
throw new RuntimeException(speaker.toString(), e);
}
}
}
class CommunicateReflectively1 {
public static <T> void preform(T speaker){
System.out.println(speaker.toString());//暗示 使用能不能使用通配符限定
//speaker.speak(); //调用失败 JAVA不支持
}
}
class CommunicateReflectivelyEx2 {
public static <T extends Isit> void preform(T speaker){
System.out.println(speaker.toString());
speaker.sit();
}
}
public class LatentReflection {
public static void main(String [] argv){
CommunicateReflectively.preform(new SmartDog());
CommunicateReflectively.preform(new Mime());
CommunicateReflectively1.preform(new SmartDog());
CommunicateReflectively1.preform(new Mime());
CommunicateReflectivelyEx2.preform(new SmartDog());
CommunicateReflectivelyEx2.preform(new Mime());
}
}