1 以一個計算器例子引入
將數據的輸入和計算(加減乘除等)都寫入主函數體內,代碼難以得到複用。
2 業務封裝
3 業務的繼承與多態
4 簡單工廠模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LxFactory
{
//聲明一個人類接口
interface Ihuman
{
void getFav(); //聲明未實現的愛好方法getFav()
string getStatus(); //聲明未實現的身份狀態(孩子,成年人)方法
}
//聲明一個抽象類Children,並實現接口的部分方法
abstract class Children : Ihuman
{
protected string _status = "孩子";
//實現接口Ihuman中的getStatus()方法
public string getStatus()
{
return _status;
}
//將接口Ihuman中的getFav()方法映射到抽象方法
abstract public void getFav();
}
//聲明一個抽象類Adult,並實現接口的部分方法
abstract class Adult : Ihuman
{
protected string _status = "成年人";
//實現接口Ihuman中的getStatus()方法
public string getStatus()
{
return _status;
}
//將接口Ihuman中的getFav()方法映射到抽象方法
abstract public void getFav();
}
//聲明男孩類Boy,繼承小孩類Children,重寫愛好方法getFav()
class Boy : Children
{
public override void getFav()
{
Console.WriteLine("男孩,我喜歡遊戲!");
}
}
//聲明女孩類Girl,繼承小孩類Children,重寫愛好方法getFav()
class Girl : Children
{
public override void getFav()
{
Console.WriteLine("女孩,我喜歡布娃娃!");
}
}
//聲明男人類Man,繼承成人類Adult,重寫愛好方法getFav()
class Man : Adult
{
public override void getFav()
{
Console.WriteLine("男人,我喜歡編程!");
}
}
//聲明女人類Woman,繼承成人類Adult,重寫愛好方法getFav()
class Woman : Adult
{
public override void getFav()
{
Console.WriteLine("女人,我喜歡逛街!");
}
}
//聲明一個抽象工廠,分別創建相應類的實例
abstract class HumanFactory
{
protected Ihuman h1 = new Boy();
protected Ihuman h2 = new Man();
protected Ihuman h3 = new Girl();
protected Ihuman h4 = new Woman();
//創建一個方法,根據不同輸入返回一個接口的引用
abstract public Ihuman getHuman(int i);
}
//聲明可以實例化各種類的工廠Factory1,繼承類HumanFactory,重寫抽象方法getHuman()
class Factory1 : HumanFactory
{
//根據不同輸入獲得不同對象所屬接口的引用
public override Ihuman getHuman(int i)
{
switch (i)
{
case 1:
return h1;
case 2:
return h2;
default:
return h1;
}
}
}
//聲明可以實例化各種類的工廠Factory1,繼承類HumanFactory,重寫抽象方法getHuman()
class Factory2 : HumanFactory
{
//根據不同輸入獲得不同對象所屬接口的引用
public override Ihuman getHuman(int i)
{
switch (i)
{
case 1:
return h3;
case 2:
return h4;
default:
return h3;
}
}
}
public class LxFactory
{
static void Main(string[] args)
{
//使用工廠1
Console.WriteLine("男性中有兩種人,請選擇編號【1】男孩【2】男人:");
int input1 = Int32.Parse(Console.ReadLine());
Factory1 f1 = new Factory1();
Ihuman h1 = f1.getHuman(input1);
h1.getFav();
Console.WriteLine("我的身份是:{0}", h1.getStatus());
//使用工廠2
Console.WriteLine("女性中有兩種人,請選擇編號【1】女孩【2】女人:");
int input2 = Int32.Parse(Console.ReadLine());
Factory2 f2 = new Factory2();
Ihuman h2 = f2.getHuman(input2);
h2.getFav();
Console.WriteLine("我的身份是:{0}", h2.getStatus());
}
}
}