//图形接口 interface Shape(){ public void draw(); } //圆形 class Circle implements Shape{ public void draw(){ System.out.println(“Circle is drawing”); } } //矩形 class Rectangle implements Shape{ public void draw(){ System.out.println(“Rectangle is drawing”); } } //图形工厂 class ShapeFactory{ public static Shape createShape(String name) throws InstantiationException, IllegalAccessException, ClassNotFoundException { //使用java的反射机制来产生对象实例 return (Shape)class.forName(name).newInstance(); } } public class ShapeDemo{ public static void draw(Shape shape){ shape.draw(); } public static void main(String[] args){ draw(ShapeFactory.createShape(“Circle”)); draw(ShapeFactory.createShape(“Rectangle”)); } }
//软件皮肤类 class Skin{ private SkinFactory skinFactory; public Skin(SkinFactory factory){ setSkinFactory(factory); } public void setSkinFactory(SkinFactory factory){ this.skinFactory = factory } public void showSkin(){ System.out.println(“Style=” + factory.getStyle().showStyle() + “, color=” + factory.getColor().showColor()); } } //软件Style interface Style(){ public void showStyle(); } //IOS style class IOSStyle implements Style{ public void showStyle(){ System.out.println(“This is IOS style”); } } //Android style class AndroidStyle implements Style{ public void showStyle(){ System.out.println(“This is Android style”); } } //软件Color interface Color(){ public void showColor(); } //IOS color class IOSColor implements Color{ public void showColor(){ System.out.println(“This is IOS color”); } } //Android color class AndroidColor implements Color{ public void showColor(){ System.out.println(“This is Android color”); } } //抽象皮肤工厂 interface SkinFactory{ public Style getStyle(); public Color getColor(); } //IOS皮肤工厂 class IOSSkinFactory implements SkinFactory{ public Style getStyle(){ return new IOSStyle(); } public Color getColor(){ return new IOSColor(); } } //Android皮肤工厂 class AndroidSkinFactory implements SkinFactory{ public Style getStyle(){ return new AndroidStyle(); } public Color getColor(){ return new AndroidColor(); } } public class SkinDemo{ public static void main(String[] args){ //显示一套IOS皮肤 Skin skin = new Skin(new IOSSkinFactory()); skin.showSkin(); //换一套Android的皮肤 skin.setSkinFactory(new AndroidSkinFactory()); skin.showSkin(); } }
//汽车接口 interface ICar{ public void run(); } //奔驰车 class BenzCar implements ICar{ public void run(){ System.out.println(“Benz car run”); } } //宝马车 class BMWCar implements ICar{ public void run(){ System.out.println(“BMW car run”); } } //抽象汽车工厂 abstract class CarFactory{ public abstract ICar createCar(); } //奔驰车工厂 class BenzCarFactory extends CarFactory{ public ICar createCar(){ return new BenzCar(); } } //宝马车工厂 class BMWCarFactory extends CarFactory{ public ICar createCar(){ return new BMWCar(); } } public class FactoryMethodDemo{ public static void main(String[] args){ CarFactory factory = new BenzCarFactory(); ICar car = factory.createCar(); car.run(); factory = new BMWCarFactory(); car = factory.createCar(); car.run(); } }