博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
反射工厂模式
阅读量:7230 次
发布时间:2019-06-29

本文共 1745 字,大约阅读时间需要 5 分钟。

[注:摘自http://www.cnblogs.com/hg98/archive/2007/06/06/774338.html]

反射工厂模式: 其实就是通过反射的方式来获得具体实例化是那个类。

 
1
namespace
ReflactionFactoryPartern
2
{
3
public
interface
IFactoryVehicle
4
{
5
IVehicle CreateVehicle();
6
}
7
}
 
1
namespace
ReflactionFactoryPartern
2
{
3
public
class
FactoryCar : IFactoryVehicle
4
{
5
public
IVehicle CreateVehicle()
6
{
7
return
new
Car();
8
}
9
}
10
}
 
1
namespace
ReflactionFactoryPartern
2
{
3
public
class
FactoryBoat : IFactoryVehicle
4
{
5
public
IVehicle CreateVehicle()
6
{
7
return
new
Boat();
8
}
9
}
10
}
 
1
namespace
ReflactionFactoryPartern
2
{
3
public
interface
IVehicle
4
{
5
void
go();
6
}
7
}
 
1
namespace
ReflactionFactoryPartern
2
{
3
public
class
Car : IVehicle
4
{
5
public
void
go()
6
{
7
Console.WriteLine(
"
This is a Car
"
);
8
}
9
}
10
}
 
1
namespace
ReflactionFactoryPartern
2
{
3
public
class
Boat : IVehicle
4
{
5
public
void
go()
6
{
7
Console.WriteLine(
"
This is a boat.
"
);
8
}
9
}
10
} 

 
1
using
System.Reflection;
2
3
 
namespace
ReflactionFactoryPartern
4
{
5
class
ReflectFactory
6
{
7
public
static
IVehicle CreateVehicleByReflect(
string
typeName)
8
{
9
string
namespaceStr
=
"
ReflactionFactoryPartern
"
;
10
string
tempChar
=
"
.
"
;
11
//
注意使用Type.GetType(String classname)时,必须指定其命名空间,否则返回为null
12
 
Type type
=
Type.GetType(namespaceStr
+
tempChar
+
typeName,
true
);
13
14
ConstructorInfo ci
=
type.GetConstructor(System.Type.EmptyTypes);
15
return
(IVehicle)ci.Invoke(
null
);
16
}
17
}
18
}

 

 
1
namespace
ReflactionFactoryPartern
2
{
3
class
Program
4
{
5
static
void
Main(
string
[] args)
6
{
7
IVehicle vechicle
=
ReflectFactory.CreateVehicleByReflect(
"
Car
"
);
8
vechicle.go();
9
Console.ReadLine();
10
}
11
}
12
}

 

转载于:https://www.cnblogs.com/Tim_Liu/archive/2010/09/03/1817259.html

你可能感兴趣的文章
介绍几个jsp页面传对象的方法
查看>>
我的Jakarta+Commons
查看>>
Bootstrap的使用
查看>>
python设置文字输出颜色
查看>>
WARNING:tornado.access:403 GET /websocket (::1) 1.00ms
查看>>
cocos creator游戏适配这事
查看>>
AngularJS - contorller app module
查看>>
CF666E. Forensic Examination
查看>>
apue第16章笔记
查看>>
Nvidia Driver
查看>>
NIO 相关解析
查看>>
Loj #2304. 「NOI2017」泳池
查看>>
面试技巧,如何通过索引说数据库优化能力,内容来自Java web轻量级开发面试教程...
查看>>
Python实现:某个用户登录后,查看自己拥有所有权限
查看>>
iOS微信朋友圈 评论点击姓名功能
查看>>
Servlet和模本办法
查看>>
static和final修饰方法
查看>>
读《认知三部曲》
查看>>
关于SVN 目录结构
查看>>
tp5页面输出时,搜索后跳转下一页的处理
查看>>