天天看點

Swift 10 組合模式 Composite Pattern

/*
大宏藥業有阿司匹林和撲熱息痛生産部門。
對於老闆、他隻需要訓示生産藥品就行。
組合模式能各控件解耦、假如想增加抗組胺藥生産部門、隻需增加此部門即可。
*/

class MedicineProduct {
	func addOrder(p_obMedicOrder : MedicineProduct) { }
	func removeOrder(p_mOrderNum : Int) { }
	func getOrder(p_mOrderNum : Int) -> MedicineProduct {
	    return MedicineProduct()
	}
	func produceMedic() { }
}

class Aspirin : MedicineProduct {
	var p_stMedicBrand : String = ""
	
	init(p_stInputMedicBrand : String) {
		p_stMedicBrand = p_stInputMedicBrand
	}
	
	override func addOrder(p_obMedicOrder : MedicineProduct) {
		print("You have no authority to add order")
	}
	
	override func removeOrder(p_mOrderNum : Int) {
		print("You have no authority to remove order")
	}
	
	override func getOrder(p_mOrderNum : Int) -> MedicineProduct {
		print("You have no authority to get order")
		return MedicineProduct()
	}
	
	override func produceMedic() {
		print("Produce \(p_stMedicBrand) aspirin")
	}
}

class Pharmacology : MedicineProduct {
	var p_stMedicBrand : String = ""
	
	init(p_stInputMedicBrand : String) {
		p_stMedicBrand = p_stInputMedicBrand
	}
	
	override func addOrder(p_obMedicOrder : MedicineProduct) {
		print("You have no authority to add order")
	}
	
	override func removeOrder(p_mOrderNum : Int) {
		print("You have no authority to remove order")
	}
	
	override func getOrder(p_mOrderNum : Int) -> MedicineProduct {
		print("You have no authority to get order")
		return MedicineProduct()
	}
	
	override func produceMedic() {
		print("Produce \(p_stMedicBrand) Pharmacology")
	}
}

class MedicineOffice : MedicineProduct {
	var p_arrMedicProduct : [MedicineProduct] = []
	var p_stMedicOfficName : String = ""
	
	func setMedicOfficName(p_stInputMedicOfficName : String) {
		p_stMedicOfficName = p_stInputMedicOfficName
	}
	
	override func addOrder(p_obMedicOrder : MedicineProduct) {
		p_arrMedicProduct.append(p_obMedicOrder)
	}
	
	override func removeOrder(p_mOrderNum : Int) {
		p_arrMedicProduct.remove(at : p_mOrderNum)
		print("remove \(p_mOrderNum) order")
	}
	
	override func getOrder(p_mOrderNum : Int) -> MedicineProduct {
		return p_arrMedicProduct[p_mOrderNum]
	}
	
	override func produceMedic() {
		print("\(p_stMedicOfficName) produces Aspirin & Pharmacology")
		
		for p_obOrder in p_arrMedicProduct {
			p_obOrder.produceMedic()
		}
	}
}

let medicineOffice = MedicineOffice()
medicineOffice.setMedicOfficName(p_stInputMedicOfficName : "Da Honge Medic Office")

var Product1 = Aspirin(p_stInputMedicBrand : "ZhangXing")
medicineOffice.addOrder(p_obMedicOrder : Product1)

var Product2 = Pharmacology(p_stInputMedicBrand : "DaTong")
medicineOffice.addOrder(p_obMedicOrder : Product2)

medicineOffice.produceMedic()

/*
Da Honge Medic Office produces Aspirin & Pharmacology
Produce ZhangXing aspirin
Produce DaTong Pharmacology
*/
           

繼續閱讀