简单工厂模式

博客展示了简单工厂模式的代码实现。定义了 IPersion 接口,有 Man 和 Woman 类实现该接口。创建了 PersionFactory 工厂类,根据传入参数返回不同对象实例。还给出了应用层代码,通过工厂类创建对象。
终于理解.
None.gif//接口
None.gif
public interface IPersion
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    void action();
ExpandedBlockEnd.gif}

None.gif
//男人类
None.gif
public class Man:IPersion
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public void action()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.Writeline(
"抽烟");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
//女人类
None.gif
public class Woman:IPersion
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public void action()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.Writeline(
"化妆");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
//工厂方法类
None.gif
public class PersionFactory
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{

//这里的逻辑处理可以改为
//将这个工厂方法类设为抽象类
//另外用一个Man和WoMan工厂类续承些类
//这样可以相对应new了
//即封装变化点
InBlock.gif    
public IPersion Factory(int i)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif         
if(i == 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif             
return new Woman().action();
ExpandedSubBlockEnd.gif         }

InBlock.gif         
else
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif             
return new Man().action();
ExpandedSubBlockEnd.gif         }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
//应用层
None.gif
public class Application
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private void Man
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif         
new PersionFactory().Factory(10);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private void Woman
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif         
new PersionFactory().Factory(1);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/sunsjorlin/archive/2005/11/28/286458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值