《Android源码设计模式解析和实战》工厂模式
工厂模式适用于复杂对象的创建:
工厂:
<pre>
public abstract class Factory {
public abstract <T extends Product> T getProduct(Class<T> cls);
}
public class RunningFactory extends Factory {
private static final String TAG = "RunningFactory";
@Override
public <T extends Product> T getProduct(Class<T> cls) {
Product p = null;
try {
p = (Product) Class.forName(cls.getName()).newInstance();
} catch (Exception e) {
Log.i(TAG, "getProduct: " + e.getMessage());
e.printStackTrace();
}
return (T) p;
}
}
</pre>
产品:
<pre>
public abstract class Product {
public abstract void start();
public abstract void end();
}
public class AProduct extends Product {
private static final String TAG = "AProduct";
@Override
public void start() {
Log.i(TAG, "start: ");
}
@Override
public void end() {
Log.i(TAG, "end: ");
}
}
public class BProduct extends Product {
private static final String TAG = "BProduct";
@Override
public void start() {
Log.i(TAG, "start: ");
}
@Override
public void end() {
Log.i(TAG, "end: ");
}
}
</pre>
使用:
<pre>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RunningFactory factory = new RunningFactory();
AProduct a = factory.getProduct(AProduct.class);
BProduct b = factory.getProduct(BProduct.class);
a.start();
b.start();
a.end();
b.end();
}
}
</pre>
log:
<pre>
03-06 19:11:34.111 26572-26572/? I/AProduct: start:
03-06 19:11:34.111 26572-26572/? I/BProduct: start:
03-06 19:11:34.111 26572-26572/? I/AProduct: end:
03-06 19:11:34.111 26572-26572/? I/BProduct: end:
</pre>