简单工厂实现的流程:
1.创建抽象产品类
2.创建具体产品的
3.创建工厂类
4.客户端调用工厂类
5.使用
下面是一个简单的示例代码,实现的功能:
提示用户输入喜欢的水果名称,调用显示该类水果的吃法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 代码操练_简单工厂
{
//1.创建抽象产品类
class Fruit
{
}
//2.创建具体产品类(苹果)
class Apple : Fruit
{
public void EatApple()
{
Console.WriteLine("我是苹果的吃法");
}
}
//创建具体产品类(香蕉)
class Banana : Fruit
{
public void EatBanana()
{
Console.WriteLine("我是香蕉的吃法");
}
}
//创建具体产品类(梨)
class Pear : Fruit
{
public void EatPear()
{
Console.WriteLine("我是梨的吃法");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("你喜欢吃什么水果:1.苹果2.香蕉3.梨");
//接受用户输入的类别
string result = Console.ReadLine();
//抽象类为空
Fruit fr = null;
//3.创建工厂类
switch (result)
{
case "苹果":
fr=new Apple();
break;
}
switch (result)
{
case "香蕉":
fr=new Banana();
break;
}
switch (result)
{
case "梨":
fr=new Pear();
break;
}
//客户端调用工厂类
if (fr is Apple)
{
((Apple)fr).EatApple();
}
if (fr is Banana)
{
((Banana)fr).EatBanana();
}
if (fr is Pear)
{
((Pear)fr).EatPear();
}
//Console.WriteLine(result);
Console.ReadKey();
}
}
}