除了直接使用new之外,还有更多制造对象的方法。工厂模式可以使实例化的活动不公开进行,也可以解决因初始化而造成的耦合问题。工厂模式是一种常见的模式,在安卓中BitmapFactory也是使用的简单工厂。
简单工厂:
public class Test { public static void main(String[] args) throws Exception{ Auto auto = (Auto) CarFactory.createCraByType("Auto"); Chev chev = (Chev) CarFactory.createCraByType("Chev"); Car car = CarFactory.createCraByType("aa"); } }
public class CarFactory { public static Car createCraByType(String carType) throws Exception{ if (carType.equals("Auto")) { return new Auto(); }else if (carType.equals("Chev")) { return new Chev(); }else { throw new Exception(){ @Override public String getMessage() { return "not find the car you want"; } }; } } }
public interface Car { } public class Auto implements Car{ public Auto() { System.out.println("auto is created"); } } public class Chev implements Car{ public Chev() { System.out.println("chev is created"); } }
工厂方法:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。其实要我理解工厂方法强调的是工厂和方法,不同的工厂有相同的方法,但是产生的却是不同工厂的产品。
public interface Car { }
public class Auto implements Car{ public Auto() { System.out.println("auto is created"); } }
public class Chev implements Car{ public Chev() { System.out.println("Chec is created"); } }
public interface CarFactory { public Car createCar(); }
public class AutoCarFactory implements CarFactory{ @Override public Car createCar() { return new Auto(); } }
public class ChevFactory implements CarFactory { @Override public Car createCar() { return new Chev(); } }
public class Test { public static void main(String[] args){ CarFactory carFactory = new AutoCarFactory(); carFactory.createCar(); carFactory = new ChevFactory(); carFactory.createCar(); } }抽象工厂:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
public class Auto implements Car{ public Auto() { System.out.println("auto is created"); } }
public class AutoCarFactory implements CarFactory{ @Override public Car createCar() { return new Auto(); } @Override public Suv createSUV() { // TODO Auto-generated method stub return new AutoSuv(); } }
public class AutoSuv extends Suv{ public AutoSuv() { System.out.println("AutoSur is created"); } }
public interface Car { }
public interface CarFactory { public Car createCar(); public Suv createSUV(); }
public class Chev implements Car{ public Chev() { System.out.println("Chec is created"); } }
public class ChevFactory implements CarFactory { @Override public Car createCar() { return new Chev(); } @Override public Suv createSUV() { // TODO Auto-generated method stub return new ChevSuv(); } }
public class ChevSuv extends Suv{ public ChevSuv() { System.out.println("ChevSuv is created"); } }
public interface Suv { }
public class Test { public static void main(String[] args){ CarFactory carFactory = new AutoCarFactory(); Car car = carFactory.createCar(); Suv suv =carFactory.createSUV(); carFactory = new ChevFactory(); car = carFactory.createCar(); suv = carFactory.createSUV(); } }