追MM与设计模式(Factory代码)

类别:编程语言 点击:0 评论:0 推荐:
FACTORY—追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,虽然口
味有所不同,但不管你带MM去麦当劳或肯德基,只管向服务员说“来四个鸡翅”就行了。
麦当劳和肯德基就是生产鸡翅的Factory

下面是我写的一个代码For Factory

//鸡翅膀基类(ChickenWing.java)
public abstract class ChickenWing
{
}

//麦当劳鸡翅膀子类(McChickenWing.java)
public class McChickenWing extends ChickenWing
{
}

//KFC鸡翅膀子类(KfcChickenWing.java)
public class KfcChickenWing extends ChickenWing
{
}

//麦当劳工厂
public class McFactory
{
public ChickenWing getChickenWing()
{
System.out.println("This is a Mcdonalds ChickenWing!");
return new McChickenWing();
}
}

//KFC工厂
public class KfcFactory
{
public ChickenWing getChickenWing()
{
System.out.println("This is a KFC ChickenWing!");
return new KfcChickenWing();
}

}

//测试java文件
public abstract class Test
{

public static void main(String[] args)
{
//new a Mc Factory
McFactory objMcFactory=new McFactory();
//new a Kfc Factory
KfcFactory objKfcFactory=new KfcFactory();

//if you and PLMM in Mcdonalds,she want to eat ChickenWing
System.out.println("You and PLMM in Mcdonalds,She Want to eat ChickenWing.
...");
System.out.print("ChickenWing have be sent to you: ");
objMcFactory.getChickenWing();
//if you and PLMM in KFC,she want to eat ChickenWing
System.out.println("You and PLMM in KFC,She Want to eat ChickenWing....");

System.out.print("ChickenWing have be sent to you: ");
objKfcFactory.getChickenWing();

}

}

输出结果:
You and PLMM in Mcdonalds,She Want to eat ChickenWing....

ChickenWing have be sent to you: This is a Mcdonalds ChickenWing!

You and PLMM in KFC,She Want to eat ChickenWing....

ChickenWing have be sent to you: This is a KFC ChickenWing!

工厂模式:客户类和工厂类分开。消费者任何时候需要某种产品,只需向工厂请求即可。
消费者无须修改就可以接纳新产品。缺点是当产品修改时,工厂类也要做相应的修改。如
:如何创建及如何向客户端提供

所以如果plmm要吃可乐或者薯条的话,除了客户端不变以外,工厂+产品都要变化,
不过这比硬编码好很多。。。
以后争取把所有追plmm的设计模式用代码写出来。。

本文地址:http://com.8s8s.com/it/it22858.htm