java工廠模式

記憶殘留發表於2016-08-07

(1)概念大白話:java工廠模式就是客戶端(main函式)要建立物件覺得麻煩就讓另外一個叫工廠的類幫它建立,然後自己每次要建立物件就叫工廠幫它弄,舉個例子,在沒有工廠這個“手下”時,客戶端要建立一個紅色衣服類 就new一個RedClothes 明天再來個 黃色衣服類YellowClothes又new了一次,不斷新增的話可能就會在客戶端(main函式)增加很多new物件的語句,為了讓客戶端爽一點,決定讓這些事情叫工廠去管理,我們把這個做法就叫做工廠模式

(2)例子:廢話多了點,先跟我花一些時間建立一下幾個類,具體代表什麼都有看

 

 程式碼 最爽的client客戶端

package cs.test;

public class Client {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        ClothesFactory clothesFactory=new ClothesFactory();
		ClothesInterfaces clothesInterfaces =clothesFactory.getByColor("yellow");
		if(clothesInterfaces!=null)
		{
			clothesInterfaces.color();
		}
	}

}

手下ClothesFactory工廠


package cs.test; public class ClothesFactory { public ClothesInterfaces getByColor(String color) { if("red".equals(color)) { return new RedClothes(); } else if("yellow".equals(color)) { return new YellowClothes(); } else return null; } }

衣服介面,因為每個衣服都有相同特質

package cs.test;

/**
 * 這是一個衣服介面
 * @author hao
 *
 */
public interface ClothesInterfaces {

	//這是一個衣服顏色的方法
	public void color();
}

紅色衣服

package cs.test;

public class RedClothes implements ClothesInterfaces {

	@Override
	public void color() {
		// TODO Auto-generated method stub
     System.out.println("這是一個紅色衣服");
	}

}

黃色衣服

package cs.test;

public class YellowClothes implements ClothesInterfaces {

	@Override
	public void color() {
		// TODO Auto-generated method stub
		System.out.println("這是一個黃色衣服");
	}

}

  

我這裡像工廠類ClothesFactory 寫得有點簡陋,有時間同學也可以完善一下,我主要是把思想說一下,這裡的client要那個物件基本不用費太多心思,想要新增建立一個藍色衣服類就寫一個藍色衣服類,然後在新增ClothesFactory 新增一個判斷就夠啦,這就是工廠模式,大家都學會了嗎?

  

  

  

相關文章