1. java设计模式连载(1)---工厂方法模式
意图:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
适用性:
- 当一个类不知道它所必须创建的对象的类的时候。
- 当一个类希望由它的子类来指定它所创建的对象的时候。
- 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
实例:
1. 定义一个生产衣服的工厂接口
package Factory_Method_Pattern;
public interface ClothesFactory {
public Clothes productClothes();
}
2. 实现这个衣服工厂接口,具体生产什么类型的衣服。
package Factory_Method_Pattern;
public class AdultClothesFactory implements ClothesFactory {
@Override
public Clothes productClothes() {
return new AdultClothes();
}
}
package Factory_Method_Pattern;
public class ChildClothesFactory implements ClothesFactory {
@Override
public Clothes productClothes() {
return new ChildClothes();
}
}
3. 定义衣服接口(衣服是用来穿的)
package Factory_Method_Pattern;
public interface Clothes{
public void dressClothes();
}
4. 实现衣服接口,什么样的衣服,什么人穿
package Factory_Method_Pattern;
public class AdultClothes implements Clothes{
@Override
public void dressClothes() {
System.out.println("大朋友衣服厂生产的衣服,大朋友穿");
}
}
package Factory_Method_Pattern;
public class ChildClothes implements Clothes{
@Override
public void dressClothes() {
System.out.println("小朋友衣服厂生产的衣服,小朋友穿");
}
}
5. 测试这个模式
package Factory_Method_Pattern;
public class Test{
public static void main(String[] args){
ClothesFactory clothesFactory = new ChildClothesFactory();
clothesFactory.productClothes().dressClothes();
ClothesFactory adultClothesFactory = new AdultClothesFactory();
adultClothesFactory.productClothes().dressClothes();
}
}
6. 多谢浏览,欢迎斧正。