1:使用场景
在任何需要生产复杂对象的地方,都可以使用工厂方法模式,用new可以完成创建对象无需使用工厂方法模式
2:UML图
3:代码举例
public abstract class Product {
public abstract void method();
}
public class ConcreteProductA extends Product{
@Override
public void method(){
System.out.println("我是具体产品A");
}
}
public class ConcreteProductB extends Product{
@Override
public void method(){
System.out.println("我是具体产品B");
}
}
public abstract class Factory {
public abstract <T extends Product> T createProduct(Class<T> clz);
}
public class ConcreteFactory extends Factory{
@Override
public <T extends Product> T createProduct(Class<T> clz){
Product p=null;
try{
p=(Product)Class.forName(clz.getName()).newInstance();
}catch(Exception e){
e.printStackTrace();
}
return (T)p;
}
}
public class Client {
public static void main(String[] args){
Factory factory =new ConcreteFactory();
Product product=factory.createProduct(ConcreteProductA.class);
product.method();
}
}
多工厂方法模式:
可以为每个产品都定义一个具体工厂,各司其职。
public class ConcreteFactoryA extends Factory{
@Override
public Product createProduct(){
return new ConcreteFactoryA();
}
}
public class ConcreteFactoryB extends Factory{
@Override
public Product createProduct(){
return new ConcreteFactoryB();
}
}
public class Client {
public static void main(String[] args){
Factory factoryA =new ConcreteFactoryA();
Product productA=factoryA.createProduct();
productA.method();
Factory factoryB =new ConcreteFactoryB();
Product productB=factoryB.createProduct();
productB.method();
}
}
简单工厂模式:
工厂类如果只有一个时,简化工厂方法模式,去掉抽象,将相应的工厂方法改为静态:
public class Factory {
@Override
public static Product createProduct(){
return new ConcreteFactoryA();
}
}
4:Android中的工厂方法模式
/**
* Decode a file path into a bitmap. If the specified file name is null,
* or cannot be decoded into a bitmap, the function returns null.
*
* @param pathName complete path name for the file to be decoded.
* @param opts null-ok; Options that control downsampling and whether the
* image should be completely decoded, or just is size returned.
* @return The decoded bitmap, or null if the image data could not be
* decoded, or, if opts is non-null, if opts requested only the
* size be returned (in opts.outWidth and opts.outHeight)
*/
public static Bitmap decodeFile(String pathName, Options opts) {
Bitmap bm = null;
InputStream stream = null;
try {
stream = new FileInputStream(pathName);
bm = decodeStream(stream, null, opts);
} catch (Exception e) {
/* do nothing.
If the exception happened on open, bm will be null.
*/
Log.e("BitmapFactory", "Unable to decode stream: " + e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// do nothing here
}
}
}
return bm;
}