简单的工厂模试

2019-04-13 16:53发布

//动物类接口
interface Animal{
//发出声音
public class sayHello(){};
}

//生产动物的工厂类
class AnimalFactory{
public static Animal createDog(){
return (Animal)new Dog();
}
}

//狗实现动物接口
class Dog implements Animal{
//狗会汪汪叫
public class sayHello(){
System.out.println("汪汪");
}
}
//外国狗实现动物接口
class EnglishDog implements Animal{
//外国狗会Wolf!Wolf!叫
public class sayHello(){
System.out.println("Wolf!Wolf!");
}
}

//测试用
class Test(){
public static void main(String [] args){
//从工厂类里面获取一只狗
Animal animal1 = AnimalFactory.createDog();
animal1.sayHello();
}
}