根据类名创建实例

Source Code 最近有人问我一个问题,就是如何根据传入的字符串,由父类生成不同的子类。当然,肯定是不希望用switch语句了,也不希望每次创建instance时,都使用reflection。我觉得解决这个问题,应该使用工厂方法来处理。解释一下自己的code,如果有更好的方法,或者有什么可以改进的地方,还望请各位不吝赐教。

Shape class 的Create调用ShapeFactory返回一个Shape class
CreateShape根据传入到shape,使用反射创建一个ShapeFactory的instance,但是只创建一次,并且使用double check来保证多线程安全。所以这里的反射只会在需要的ShapeFactory不存在的时候才会创建,所以只是在第一次创建想要的shape时,才会使用到反射,以后都是直接使用instance

WinShape project: (class library)   
None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
using  System.Reflection;
None.gif
None.gif
namespace  WinShape
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public abstract class Shape
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public abstract string Draw();
InBlock.gif
InBlock.gif        
public static Shape Create(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return ShapeFactory.CreateShape(name);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif
InBlock.gif    
public class Line : Shape
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
public override string Draw()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return "Draw Line:  -----------------";
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public class Circle : Shape
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public override string Draw()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return "Draw Circle: OOOOOOOOOOOOOOOO";
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public class Triangle : Shape
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public override string Draw()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return "Draw Triangle: ^^^^^^^^^^^^^^";
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
internal abstract class ShapeFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private static Dictionary<string, ShapeFactory> factories = new Dictionary<string, ShapeFactory>();
InBlock.gif
InBlock.gif        
protected abstract Shape GetShape();
InBlock.gif
InBlock.gif        
internal static Shape CreateShape(string shapeName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif               
//double check to prevent create multiple instances by multiple threads
InBlock.gif
               if(!factories.ContainsKey(shapeName)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif               
dot.gif{
InBlock.gif                   
lock (factories)
ExpandedSubBlockStart.gifContractedSubBlock.gif                   
dot.gif{
InBlock.gif                       
if (!factories.ContainsKey(shapeName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                       
dot.gif{
InBlock.gif                           Assembly assembly 
= Assembly.GetExecutingAssembly();
InBlock.gif                           Type t 
= assembly.GetType(string.Format("WinShape.ShapeFactory+{0}Factory", shapeName));
InBlock.gif                           
if (t == null)
InBlock.gif                               
return null;
InBlock.gif                           ShapeFactory factory 
= System.Activator.CreateInstance(t) as ShapeFactory;
InBlock.gif                           factories.Add(shapeName, factory);
ExpandedSubBlockEnd.gif                       }

ExpandedSubBlockEnd.gif                   }

ExpandedSubBlockEnd.gif               }

InBlock.gif
InBlock.gif               ShapeFactory fac 
= factories[shapeName];
InBlock.gif               
return fac.GetShape();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private class LineFactory : ShapeFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
protected override Shape  GetShape()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return new Line();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private class CircleFactory : ShapeFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
protected override Shape GetShape()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return new Circle();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private class TriangleFactory : ShapeFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
protected override Shape GetShape()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return new Triangle();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
InBlock.gif    
ExpandedBlockEnd.gif}

None.gif

window application:

Form1.Design.cs
None.gif    private  System.Windows.Forms.Button btnCreate;
None.gif        
private  System.Windows.Forms.ComboBox cmbClassNames;
None.gif        
private  System.Windows.Forms.Button button1;
None.gif        
private  System.Windows.Forms.TextBox textBox1;
None.gif        
private  System.Windows.Forms.Label label1;
None.gif        
private  System.Windows.Forms.Label label2;

Form1.cs
None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.ComponentModel;
None.gif
using  System.Data;
None.gif
using  System.Drawing;
None.gif
using  System.Text;
None.gif
using  System.Windows.Forms;
None.gif
using  System.Reflection;
None.gif
using  WinShape;
None.gif
None.gif
namespace  CreateInstanceByClassName
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public partial class Form1 : Form
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public Form1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            InitializeComponent();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnCreate_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (this.cmbClassNames.SelectedIndex < 0)
InBlock.gif                
return;
InBlock.gif
InBlock.gif            
string shapeName = this.cmbClassNames.Items[this.cmbClassNames.SelectedIndex].ToString();
InBlock.gif
InBlock.gif            Shape shape 
= Shape.Create(shapeName);
InBlock.gif
InBlock.gif            
if (shape != null)
InBlock.gif                
this.textBox1.Text = shape.Draw();
InBlock.gif            
else
InBlock.gif                
this.textBox1.Text = "Null Reference";
InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void Form1_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Assembly assembly 
= Assembly.Load("WinShape");
InBlock.gif
InBlock.gif            Type shapeType 
= assembly.GetType("WinShape.Shape");
InBlock.gif
InBlock.gif            Type[] types 
= assembly.GetTypes();
InBlock.gif
InBlock.gif            
foreach (Type t in types)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (t.IsSubclassOf(shapeType) && !t.IsAbstract)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.cmbClassNames.Items.Add(t.Name);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button1_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.Close();
InBlock.gif            Application.Exit();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


转载于:https://www.cnblogs.com/redpeachsix/archive/2007/07/11/814069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值