java设计模式连载(1)---工厂方法模式

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. 多谢浏览,欢迎斧正。

  

     

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值