泛型-使用泛型结合工厂方法实现单例模式,以支持类型自定义
package my; public class Factory<T> { static final Factory<Unicycle> t1=new Factory<Unicycle>(); static final Factory<Tricycle> t2=new Factory<Tricycle>(); static final Factory<Bicycle> t3=new Factory<Bicycle>(); private Cycle createCyc(){ if(this.equals(t1)){ System.out.println("创建了一个Unicycle"); return new Unicycle(); } if(this.equals(t2)){ System.out.println("创建了一个Tricycle"); return new Tricycle(); } if(this.equals(t3)){ System.out.println("创建了一个Bicycle"); return new Bicycle(); } return null; } public static Factory<?> create(String FacName){ if(FacName.equals("Unicycle"))return t1; if(FacName.equals("Tricycle"))return t2; if(FacName.equals("Bicycle"))return t3; return null; } private Factory(){ } public Factory(String FacName){ } public static void main(String[] args){ Factory<?> UniFac1=Factory.create("Unicycle"); UniFac1.createCyc(); Factory<?> TriFac1=Factory.create("Tricycle"); TriFac1.createCyc(); Factory<?> UniFac2=Factory.create("Unicycle"); UniFac2.createCyc(); } } class Unicycle implements Cycle{ Unicycle(){} } class Tricycle implements Cycle{ Tricycle(){} } class Bicycle implements Cycle{ Bicycle(){} }
package my; public interface Cycle { //由于题目并没有涉及Cycle的功能,所以不需要多配置属性和方法 }