面向对象编程(OOP)概念入门及更多
本文旨在帮助理解OOP概念,重点关注.NET/C#。本文以问答形式编写,易于理解。
目录
- 引言
- 背景
- 必备组件
- 主要内容
- 什么是软件架构?
- 为什么架构很重要?
- 什么是OOP?
- 什么是对象?
- 什么是类?
- 如何识别和设计类?
- 什么是封装(或信息隐藏)?
- 什么是关联?
- 关联、聚合和组合之间有什么区别?
- 什么是抽象和泛化?
- 什么是抽象类?
- 什么是接口?
- 类和接口之间有什么区别?
- 接口和抽象类之间有什么区别?
- 什么是隐式和显式接口实现?
- 什么是继承?
- 什么是多态?
- 什么是方法重载?
- 什么是运算符重载?
- 什么是方法重写?
- 什么是用例?
- 什么是类图?
- 什么是包图?
- 什么是序列图?
- 什么是两层架构?
- 什么是三层架构?
- 什么是MVC架构?
- 什么是SOA?
- 什么是数据访问层?
- 什么是业务逻辑层?
- 什么是四人帮(GoF)设计模式?
- 抽象工厂和生成器设计模式之间有什么区别?
- 结论是什么?
- 我参考了什么?
- 历史
1. 引言
我注意到近几个月来,Code Project上“架构”类别的文章数量有所增加。大多数文章的读者数量也很高,尽管文章的评分并不高。这表明读者对架构文章感兴趣,但质量未能达到他们的期望。本文旨在构建性地组织/定义/解释所有软件架构的入门概念,供那些希望迈向系统架构师下一步的资深开发人员参考。
有一天,我读到一篇文章,说最富有的2%人口拥有世界一半的财富。它还说,2000年,最富有的1%的成年人拥有全球资产的40%。此外,最富有的10%的成年人占世界总财富的85%。因此,在现实世界中存在着财富分配不均的现象。你有没有想过软件世界中知识分配不均的现象?在我看来,软件行业的蓬勃发展迫使开发人员使用已实现的库、服务和框架,在越来越短的时间内开发软件。新开发人员被训练(我更倾向于说更频繁地)使用已开发的软件组件来更快地完成开发。他们只需插入一个现有库,就能设法满足需求。但故事的悲伤之处在于,他们从未接受过定义、设计架构和实现此类组件的培训。随着时间的推移,这些开发人员会成为主管和软件架构师。他们的头衔变了,但没有理解、没有架构经验的陈旧遗留问题仍在继续,造成了优秀架构师的真空。底线是,只有一小部分开发人员知道如何设计一个真正的面向对象系统。这个问题变得越来越难解决,因为软件行业的侵略性不容许对现有流程进行轻松调整,而且相关的在线教学材料要么复杂,要么不实用,要么有时甚至是错误的。其中大部分使用不切实际、不相关的形状、动物和其他物理世界实体的例子来教授软件架构的概念。只有很少的优秀商业导向的设计参考。不幸的是,我自己也不例外,也是这个系统本身的产物。我接受了和你们一样的教育,也参考了你们都读过的相同资源。
回到最初的一点,我注意到,在懂得如何正确构建系统的架构师和其他人之间,存在着一个日益扩大的知识差距。懂得的人,知道得对。但不懂的人,一无所知。就像世界的财富分配一样,这是知识的失衡分配。
2. 背景
本文是在阅读和听到新开发人员对软件架构基础知识的提问后开始的。市面上有一些不错的文章,但开发人员仍然难以理解基本概念,更重要的是,难以理解如何正确应用它们。
在我看来,新手总是难以理解一个新概念的精确定义,因为这是一个新生的、因此陌生的想法。有经验的人理解其含义,但没有经验的人则难以理解其定义本身。就是这样。雇主想要有经验的员工。所以他们说,你需要有经验才能找到工作。但如果没有人愿意给你工作,一个人又该如何获得经验呢?和普遍情况一样,软件架构的起点也不例外。这会很困难。当你开始设计第一个系统时,你会尝试应用你所知道或从任何地方学到的一切。你会觉得每个类都需要定义一个接口,就像我曾经做过的那样。你会发现很难理解何时该做什么,何时不该做什么。准备好经历痛苦的过程吧。别人会批评你,可能会嘲笑你,说你的设计是错的。听取他们的意见,并不断学习。在这个过程中,你还需要大量阅读和思考。我希望本文能为你这段漫长的旅程提供一个正确的开端。
“通过对同时代事务的长期经验和对古代的持续研究,获得的伟大人物行为的知识”——我在读《孙子兵法》时读到这句话,它在这里似乎很适用,不是吗?
3. 先决条件
本文旨在为新开发人员提供一个关于软件架构基础知识的准确信息库,重点关注面向对象编程(OOP)。如果您是一名具有至少三年持续开发经验并渴望学习更多、迈向下一个层面成为软件架构师的开发人员,那么本文适合您。
4. 主要内容
4.1. 什么是软件架构?
软件架构被定义为指导
- 将问题和要构建的系统划分为离散的部分
- 用于创建这些部分之间接口的技术
- 用于管理整体结构和流程的技术
- 用于将系统与其环境接口的技术
- 开发和交付方法、技术和工具的适当使用
4.2. 为什么架构很重要?
软件架构的主要目标是定义系统的非功能性需求和定义环境。详细设计之后是关于如何在架构规则内实现功能行为的定义。架构很重要,因为它
- 控制复杂性
- 强制执行最佳实践
- 提供一致性和统一性
- 提高可预测性
- 实现重用
4.3. 什么是OOP?
OOP是一种设计理念。它代表面向对象编程。面向对象编程(OOP)使用与旧的面向过程编程语言(C、Pascal等)不同的编程语言集。OOP中的一切都被归类为自给自足的“对象”。因此,您可以通过四种主要的面向对象编程概念来获得可重用性。
为了清楚地理解面向对象模型,让我们以您的“手”为例。“手”是一个类。您的身体有两个“手”类型的对象,分别命名为“左手”和“右手”。它们的主要功能由通过肩膀(通过接口)发送的一组电信号控制或管理。因此,肩膀是您的身体用来与手交互的接口。手是一个设计良好的类。通过稍微改变其属性,手被重用于创建左手和右手。
4.4. 什么是对象?
对象可以被认为是“事物”,它可以执行一组相关的活动。对象执行的活动集定义了对象的行为。例如,手(对象)可以抓取东西,或者学生(对象)可以给出他们的姓名或地址。
在纯OOP术语中,对象是类的实例。
4.5. 什么是类?
类仅仅是对象的一种表示。它是描述对象细节的蓝图、计划或模板。类是创建单个对象的蓝图。类由三部分组成:名称、属性和操作。
public class Student
{
}
根据下面的示例,我们可以说,名为objectStudent
的Student
对象是从Student
类创建的。
Student objectStudent = new Student();
在现实世界中,您经常会发现许多同种类的个体对象。例如,可能存在数千辆其他自行车,它们都具有相同的品牌和型号。每辆自行车都是根据相同的蓝图制造的。用面向对象的术语来说,我们说自行车是被称为自行车的对象类的实例。
在软件世界中,尽管您可能没有意识到,但您已经使用了类。例如,您一直使用的TextBox
控件是由TextBox
类制成的,该类定义了它的外观和功能。每次拖动TextBox
控件时,您实际上是在创建一个TextBox
类的*.new*实例。
4.6. 如何识别和设计类?
这是一门艺术;每个设计师使用不同的技术来识别类。但是,根据面向对象设计原则,在设计类时必须遵循五个原则
- SRP - 单一职责原则 - 一个类应该只有一个,且只有一个,改变的理由。
- OCP - 开放封闭原则 - 应该能够扩展任何类的行为,而不修改这些类
- LSP - 里氏替换原则 - 派生类必须能够替换其基类。
- DIP - 依赖倒置原则 - 依赖抽象,而非具体实现
- ISP - 接口隔离原则 - 创建针对客户端的精细接口
有关设计原则的更多信息,请参阅Object Mentor。
此外,要正确识别类,您需要识别系统叶级函数的完整列表(系统的粒度级别的用例)。然后,您可以继续将每个函数分组以形成类(类将分组相同类型的函数或操作)。但是,一个定义良好的类必须是对一组函数的有意义的 agrupación,并应支持重用,同时增加整个系统的可扩展性或可维护性。
在软件世界中,分而治之的概念始终是推荐的,如果您一开始就分析整个系统,您会发现很难管理。因此,更好的方法是首先识别系统的模块,然后深入研究每个模块以找出类。
一个软件系统可能包含许多类。当您有很多类时,就需要进行管理。想象一个大组织,其劳动力超过数千名员工(我们取一名员工为一个类)。为了管理这样的劳动力,您需要有适当的管理政策。相同的技术可以应用于管理您的软件系统的类。为了管理软件系统的类并降低复杂性,系统设计者使用几种技术,这些技术可以分为四个主要概念,称为
- 封装
- 抽象
- 继承
- 多态
这些概念是OOP世界的四大神,在软件术语中,它们被称为四个主要的面向对象编程(OOP)概念。
4.7. 什么是封装(或信息隐藏)?
封装是将程序对象中运行该对象所需的所有资源(主要是方法和数据)包含在内。在OOP中,封装主要通过创建类来实现,类公开public
方法和属性。类是一种容器、胶囊或细胞,它封装了一组方法、属性和特性,以为其他类提供其预期的功能。从这个意义上说,封装还允许类在其不影响系统整体功能的情况下更改其内部实现。封装的目的是隐藏类的业务实现方式,同时允许其他类对其提出请求。
为了模块化/定义一个类的功能,该类可以通过多种不同的方式使用另一个类公开的函数或属性。根据面向对象编程,类之间有几种链接技术。这些技术称为关联、聚合和组合。
封装还有其他几种用法,例如,我们可以采用接口的使用。接口可用于隐藏已实现类的*.information*。
IStudent myLStudent = new LocalStudent();
IStudent myFStudent = new ForeignStudent();
根据上图(假设LocalStudent
和ForeignStudent
类都实现了IStudent
接口),我们可以看到LocalStudent
和ForeignStudent
如何通过IStudent
接口隐藏其本地化实现。
在这两种情况下,例如,‘myLStudent
’和‘myFStudent
’的类型都是IStudent
,但它们都承载着两个独立的本地和*.foreign*实现。这样,对‘myLStudent
’和‘myFStudent
’对象调用‘DoLearn
(object)’将触发它们各自的*.foreign*和本地实现。这样,承载‘ForeignStudent
’的‘myFStudent
’将触发带有*.foreign*教学大纲的相应学习功能,而另一个带有‘LocalStudent
’的将触发带有本地教学大纲的学习功能。
4.8. 什么是关联?
关联是两个类之间的(*a*)关系。它允许一个对象实例代表另一个对象执行某个*.action*。关联是定义两个类之间关系的更通用术语,而聚合和组合相对*.special*。
public class StudentRegistrar
{
public StudentRegistrar ();
{
new RecordManager().Initialize();
}
}
在这种情况下,我们可以说StudentRegistrar
和RecordManager
之间存在关联,或者从StudentRegistrar
到RecordManager
存在*.directional*关联,或者StudentRegistrar
*使用*(*Use*)RecordManager
。由于明确指定了方向,在这种情况下,控制器类是StudentRegistrar
。
对一些初学者来说,关联是一个令人困惑的概念。麻烦*.created*不仅是由关联本身造成的,还有另外两个*OOP*概念,即关联、聚合和组合。在描述聚合和组合之前,每个人都理解关联。聚合或组合不能*.separately*理解。如果您*.only*理解了聚合,它就会*.crack*与关联给出的定义相冲突,如果您试图*.only*理解组合,它*.always**.threaten*与聚合给出的定义相冲突,这三个概念*.closely*.related,因此*.must*.studed*.together*,通过*.comparing*.one*.definition*.to*.another。让我们*.explore*.all*.three*.and*.see*.whether*.we*.can*.understand*.the*.differences*.between*.these*.useful*.concepts。
4.9. 关联、聚合和组合之间有什么区别?
关联是两个类之间的一种*has-a*
关系,其中没有特定的所有权。它只是两个类之间的连接。当您在*.another*类中定义一个类的变量时,您就启用了第一个类对第二个类的*.functions*和*.properties*的*关联*。然后,聚合和组合都是关联的*.types*。
聚合是一种*弱*类型的关联,具有*部分*所有权。对于聚合关系,我们使用术语*uses*
来表示*弱**has-a*
关系。这比组合要弱。然后,*weak*意味着聚合器的*.linked*.components*.may*.survive*.the*.aggregations*.life-cycle*.without*.the*.existence*.of*.their*.parent*.objects。例如,一个学校系*uses*
老师。任何老师*.may*.belong*.to*.more*.than*.one*.department。因此,如果一个系*.ceases*.to*.exist*,*.teacher*.will*.still*.exist*。
另一方面,组合是一种*强*类型的关联,具有*完全*所有权。这比*.weak*.聚合*.strong*。对于组合关系,我们使用术语*owns*
来表示*强**has-a*
关系。例如,一个系*owns*
课程,这意味着任何课程的生命周期*.depend*.on*.the*.department's*.life-cycle*。因此,如果一个系*.ceases*.to*.exist*,*.underlying*.courses*.will*.cease*.to*.exist*.as*.well*。
当没有所有权时,我们将这种关系视为关联,我们*.simply*.use*.the*.*has-a*
*.term*,或者有时*.verb*描述*.relationship*。例如,一位老师*has-a*
或*teaches*
一个学生。老师和学生之间没有所有权,*.each*.has*.their*.own*.life-cycle*。
public class University
{
private Chancellor universityChancellor = new Chancellor();
}
在上例中,我可以*.say*,University
*.aggregate*.Chancellor
或University
*.has*.an*.(*has-a*).Chancellor
。但即使*.without*.aChancellor
,University
*.can*.exists*。但Faculties*.cannot*.exist*.without*.theUniversity
,Faculty
(或Faculties
)的*.life*.time*.attached*.with*.the*.life*.time*.of*.theUniversity
。如果University
*.is*.disposed*,*.Faculties**.will*.not*.exist*。在这种情况下,我们称University
*.is*.composed*.of*Faculties。因此,这种组合可以*.recognized*.as*.a*.special*.type*(*strong*.kind)*.of*.an*.aggregation*。
同样,作为另一个*.example*,*.you*.can*.say*,KeyValuePairCollection
和KeyValuePair
之间存在*.composite*.relationship*。就像*.Faculty*.and*.the*.University*.一样,*.the*.two*.mutually*.depend*.on*.each*.other*。
.NET和Java使用Composite*.relation*.来定义它们的*.Collections*。我*.see*.Composition*.being*.used*.in*.many*.other*.ways*.too*。但是,*.more*.important*.factor*,*.that*.most*.people*.forget*.is*.the*.life*.time*.factor*。*.two*.classes*.that*.has*.bond*.with*.a*.composite*.relation*.mutually*.depend*.on*.each*.other*。如果您*.take*.the*.NET*.Collection*.to*.understand*.this*,*.there*.you*.have*.the*.Collection*.element*.define*.inside*(*.it*.is*.an*.inner*.part*,*.hence*.called*.it*.is*.composed*.of)*.the*.Collection*,*.farcing*.the*.Element*.to*.get*.disposed*.with*.the*.Collection*。如果*.not*,*.as*.an*.example*,*.if*.you*.define*.the*.Collection*.and*.its*.Element*.to*.be*.independent*,*.then*.the*.relationship*.would*.be*.more*.of*.a*.type*.Aggregation*,*.than*.a*.Composition*。*.so*.the*.point*.is*,*.if*.you*.want*.to*.bind*.two*.classes*.with*.Composite*.relation*,*.more*.accurate*.way*.is*.to*.have*.a*.one*.define*.inside*.the*.other*.class*(*.making*.it*.a*.protected*.or*.private*.class)*。*.this*.way*,*.you*.are*.allowing*.the*.outer*.class*.to*.fulfill*.its*.purpose*,*.while*.tying*.the*.lifetime*.of*.the*.inner*.class*.with*.the*.outer*.class*。
所以*.summary*,*.we*.can*.say*.that*.aggregation*.is*.a*.special*.kind*.of*.an*.association*.and*.composition*.is*.a*.special*.kind*.of*.an*.aggregation*。(*Association->Aggregation->Composition*)
4.10. 什么是抽象和泛化?
抽象是对思想、品质和特性的强调,而不是细节(细节的压制)。抽象的重要性源于其隐藏无关细节的能力以及使用名称引用对象。抽象在程序构建中至关重要。它强调对象是什么或做什么,而不是它如何表示或如何工作。因此,它是管理大型程序复杂性的主要手段。
虽然抽象通过隐藏无关细节来减少复杂性,但泛化通过用单个构造体替换执行相似功能的多个实体来减少复杂性。泛化是应用程序的扩展,以涵盖更大范围的相同或不同类型的对象。编程语言通过变量、参数化、泛型和*多态*提供*.generalization*。它强调对象之间的*.similarity*。因此,它有助于通过将个体*.collect*.into*.groups*.并提供*.representative*.来管理复杂性,该*.representative*可用于*.specify*.该*.group*.的任何*.individual*。
抽象和泛化*.often*.used*.together*。抽象*.are*.generalized*.through*.parameterization*.to*.provide*.greater*.utility*。在参数化中,实体的一个或多个部分被替换为一个*.new*.名称。该名称用作参数。当调用参数化的*.abstract*时,它*.is*.invoked*.with*.a*.binding*.of*.the*.parameter*.to*.an*.argument*。
4.11. 什么是抽象类?
使用abstract
关键字声明的抽象类*.cannot*.be*.instantiated*。它*.can*.only*.be*.used*.as*.a*.super-class*.for*.other*.classes*.that*.extend*.theabstract
*.class*。Abstract
*.class*.is*.the*.concept*.and*.implementation*.gets*.completed*.when*.it*.is*.being*.realized*.by*.a*.subclass*。*.in*.addition*.to*.this*,*.a*.class*.can*.inherit*.only*.from*.oneabstract
*.class*(*.but*.a*.class*.may*.implement*.many*.interfaces)*.and*.must*.override*.all*.its*.methods*/*properties*.that*.are*.declared*.to*.beabstract
*.and*.may*.override*.virtual*.methods*/*properties*。
Abstract
*.classes*.are*.ideal*.when*.implementing*.frameworks*。*.as*.an*.example*,*.let's*.study*.theabstract
*.class*.namedLoggerBase
*.below*。*.please*.carefully*.read*.the*.comments*.as*.it*.will*.help*.you*.to*.understand*.the*.reasoning*.behind*.this*.code*
public abstract class LoggerBase
{
/// <summary>
/// field is private, so it intend to use inside the class only
/// </summary>
private log4net.ILog logger = null;
/// <summary>
/// protected, so it only visible for inherited class
/// </summary>
protected LoggerBase()
{
// The private object is created inside the constructor
logger = log4net.LogManager.GetLogger(this.LogPrefix);
// The additional initialization is done immediately after
log4net.Config.DOMConfigurator.Configure();
}
/// <summary>
/// When you define the property as abstract,
/// it forces the inherited class to override the LogPrefix
/// So, with the help of this technique the log can be made,
/// inside the abstract class itself, irrespective of its origin.
/// If you study carefully, you will find a reason for not to have “set” method here.
/// </summary>
protected abstract System.Type LogPrefix
{
get;
}
/// <summary>
/// Simple log method,
/// which is only visible for inherited classes
/// </summary>
/// <param name="message"></param>
protected void LogError(string message)
{
if (this.logger.IsErrorEnabled)
{
this.logger.Error(message);
}
}
/// <summary>
/// Public properties which expose to inherited class
/// and all other classes that have access to inherited class
/// </summary>
public bool IsThisLogError
{
get
{
return this.logger.IsErrorEnabled;
}
}
}
将此类作为abstract
的*.idea*.is*.to*.define*.a*.framework*.for*.exception*.logging*。*.this*.class*.will*.allow*.all*.subclasses*.to*.gain*.access*.to*.a*.common*.exception*.logging*.module*.and*.will*.facilitate*.to*.easily*.replace*.the*.logging*.library*。*.by*.the*.time*.you*.define*.theLoggerBase
,*.you*.wouldn’t*.have*.an*.idea*.about*.other*.modules*.of*.the*.system*。*.but*.you*.do*.have*.a*.concept*.in*.mind*.and*.that*.is*,*.if*.a*.class*.is*.going*.to*.log*.an*.exception*,*.they*.have*.to*.inherit*.theLoggerBase
*。*.in*.other*.words*,*.theLoggerBase
*.provides*.a*.framework*.for*.exception*.logging*。
让我们*.try*.to*.understand*.each*.line*.of*.the*.above*.code*。
与其他*.class*.一样,abstract
*.class*.可以*.contain*.fields*,*.hence*.I*.used*.aprivate
*.field*.namedlogger
*.declare*.theILog
*.interface*.of*.the*.famouslog4net
*.library*。*.this*.will*.allow*.theLoggerbase
*.class*.to*.control*,*.what*.to*.use*,*.for*.logging*,*.hence*,*.will*.allow*.changing*.the*.source*.logger*.library*.easily*。
LoggerBase
*.constructor*.的*.access*.modifier*.isprotected
*。*.public*.constructor*.has*.no*.use*.when*.the*.class*.is*.of*.typeabstract
*。*.abstract*.classes*.are*.not*.allowed*.to*.instantiate*.the*.class*。*.so*.I*.went*.for*.theprotected
*.constructor*。
名为LogPrefix
*.的*.abstract
*.property*.is*.an*.important*.one*。*.it*.enforces*.and*.guarantees*.to*.have*.a*.value*.forLogPrefix
(LogPrefix
*.uses*.to*.obtain*.the*.detail*.of*.the*.source*.class*,*.which*.the*.exception*.has*.occurred)*.for*.every*.subclass*,*.before*.they*.invoke*.a*.method*.to*.log*.an*.error*。
名为LogError
*.的*.method*.is*.protected*,*.hence*.exposed*.to*.all*.subclasses*。*.you*.are*.not*.allowed*.or*.rather*.you*.cannot*.make*.itpublic
*,*.as*.any*.class*,*.without*.inheriting*.theLoggerBase
*.cannot*.use*.it*.meaningfully*。
让我们*.find*.out*.why*.the*.property*.namedIsThisLogError
*.ispublic
*。*.it*.may*.be*.important*/*useful*.for*.other*.associated*.classes*.of*.an*.inherited*.class*.to*.know*.whether*.the*.associated*.member*.logs*.its*.errors*.or*.not*。
*.apart*.from*.these*,*.you*.can*.also*.havevirtual
*.methods*.defined*.in*.anabstract
*.class*。*.thevirtual
*.method*.may*.have*.its*.default*.implementation*,*.where*.a*.subclass*.can*.override*.it*.when*.required*。
*.all*.and*.all*,*.the*.important*.factor*.here*.is*.that*.all*OOP*.concepts*.should*.be*.used*.carefully*.with*.reasons*,*.you*.should*.be*.able*.to*.logically*.explain*,*.why*.you*.make*.a*.property*.apublic
*.or*.a*.field*.aprivate
*.or*.a*.class*.anabstract
*。*.additionally*,*.when*.architecting*.frameworks*,*.the*OOP*.concepts*.can*.be*.used*.to*.forcefully*.guide*.the*.system*.to*.be*.developed*.in*.the*.way*.framework*.architect’s*.wanted*.it*.to*.be*.architected*.initially*。
4.12. 什么是接口?
*.summary*,*.the*.Interface*.separates*.the*.implementation*.and*.defines*.the*.structure*,*.and*.this*.concept*.is*.very*.useful*.in*.cases*.where*.you*.need*.the*.implementation*.to*.be*.interchangeable*。*.apart*.from*.that*,*.an*.interface*.is*.very*.useful*.when*.the*.implementation*.changes*.frequently*。*.some*.say*.you*.should*.define*.all*.classes*.in*.terms*.of*.interfaces*,*.but*.I*.think*.recommendation*.seems*.a*.bit*.extreme*。
接口可用于定义一个通用模板,然后一个或多个abstract
类来定义接口的部分实现。接口*.only*.specify*.the*.method*.declaration*(*.implicitlypublic
*.andabstract
)*.and*.can*.contain*.properties*(*.which*.are*.also*.implicitlypublic
*.andabstract
)*。*.interface*.definition*.begins*.with*.the*.keyword*.interface*。*.an*.interface*.like*.that*.of*.anabstract
*.class*.cannot*.be*.instantiated*。
如果*.一个*.实现*.接口的*.类*.没有*.定义*.接口中的*.所有*.方法*,*.那么*.它*.必须*.被*.声明*.为abstract
*,*.并且*.方法*.定义*.必须*.由*.扩展*.该abstract
*.类的*.子类*.提供*。*.in*.addition*.to*.this*,*.an*.interface*.can*.inherit*.other*.interfaces*。
下面的*.sample*.将*.为*.我们*.的LoggerBase
abstract
*.类*.提供*.一个*.interface*。
public interface ILogger
{
bool IsThisLogError { get; }
}
4.13. 类和接口之间有什么区别?
在*.NET*/*C#*中,*.class*.可以*.被*.定义*.为*.实现*.一个*.interface*,*.并且*.它*.也*.支持*.*.multiple*.implementations*。*.when*.aclass
*.implements*.an*.interface*,*.an*.object*.of*.such*.class*.can*.be*.encapsulated*.inside*.an*.interface*。
如果MyLogger
*.是*.一个*.类*,*.which*.implementsILogger
*,*.there*.we*.can*.write*
ILogger log = new MyLogger();
*.class*.和*.interface*.是*.两个*.不同的*.类型*(*.conceptually*)*。*.theoretically*,*.aclass
*.emphasizes*.the*.idea*.of*.encapsulation*,*.while*.aninterface
*.emphasizes*.the*.idea*.of*.abstraction*(*.by*.suppressing*.the*.details*.of*.the*.implementation*)*。*.the*.two*.pose*.a*.clear*.separation*.from*.one*.to*.another*。*.therefore*,*.it*.is*.very*.difficult*.or*.rather*.impossible*.to*.have*.an*.effective*.meaningful*.comparison*.between*.the*.two*,*.but*.it*.is*.very*.useful*.and*.also*.meaningful*.to*.have*.a*.comparison*.between*.an*.interface*.and*.an*.abstract*.class*。
4.14. 接口和抽象类之间有什么区别?
接口和抽象类之间有很大的*.difference*,*.even*.though*.both*.look*.similar*
- 接口定义以关键字
interface
开头,因此它是*.type*.interface*。 - 抽象类使用
abstract
关键字声明,因此它是class
*.type*。 - 接口*.没有*.实现*,*.但*.它们*.必须*.被*.实现*。
- 抽象类的*.methods*.可以*.有*.*.own*.default*.implementations*,*.and*.they*.may*.be*.extended*。*.Abstract*.class's*.methods*.could*.run*.independent*.of*.the*.inheriting*.class*。
- 接口*.只能*.有*.方法*.声明*(*.implicitly
public
*.andabstract
)*.and*.properties*(*.implicitlypublic static
*)* - 抽象类*.的*.methods*.*.can’t*.have*.implementation*.only*.when*.declared
abstract
*。 - 接口*.可以*.继承*.*.more*.than*.one*.interface*。
- 抽象类*.可以*.实现*.*.more*.than*.one*.interface*,*.but*.can*.inherit*.only*.one*.class*。
- 抽象类*.必须*.覆盖*.所有*.*.abstract*.methods*.and*.may*.override*.virtual*.methods*。
- 当*.实现*.*.changing*时,*.interface*.可以*.被*.使用*。
- 抽象类*.可以*.用于*.为*.*.base*.class*.提供*.*.default*.behavior*。
- 接口*.使*.实现*.*.interchangeable*。
- 接口*.通过*.隐藏*.实现*.*.increase*.security*。
- 抽象类*.可以*.用于*.*.implementing*.framework*。
- 抽象类*.是*.*.excellent*.way*.to*.create*.planned*.inheritance*.hierarchies*.and*.also*.to*.use*.as*.non-leaf*.classes*.in*.class*.hierarchies*。
抽象类*.允许*.你*.定义*.*.some*.behaviors*;*.they*.force*.your*.subclasses*.to*.provide*.others*。*.as*.an*.example*,*.if*.you*.have*.an*.application*.framework*,*.an*.abstract*.class*.can*.be*.used*.to*.provide*.the*.default*.implementation*.of*.the*.services*.and*.all*.mandatory*.modules*.such*.as*.event*.logging*.and*.message*.handling*,*.etc*。*.this*.approach*.allows*.the*.developers*.to*.develop*.the*.application*.within*.the*.guided*.help*.provided*.by*.the*.framework*。
*.however*,*.in*.practice*,*.when*.you*.come*.across*.with*.some*.application-specific*.functionality*.that*.only*.your*.application*.can*.perform*,*.such*.as*.startup*.and*.shutdown*.tasks*,*.etc*。*.the*.abstract*.base*.class*.can*.declare*.virtual*.shutdown*.and*.startup*.methods*。*.the*.base*.class*.knows*.that*.it*.needs*.those*.methods*,*.but*.an*.abstract*.class*.lets*.your*.class*.admit*.that*.it*.doesn't*.know*.how*.to*.perform*.those*.actions*;*.it*.only*.knows*.that*.it*.must*.initiate*.the*.actions*。*.when*.it*.is*.time*.to*.start*.up*,*.the*.abstract*.class*.can*.call*.the*.startup*.method*。*.when*.the*.base*.class*.calls*.this*.method*,*.it*.can*.execute*.the*.method*.defined*.by*.the*.child*.class*。
4.15. 什么是隐式和显式接口实现?
*.as*.mentioned*.before*,*.NET*.supports*.multiple*.implementations*,*.the*.concept*.of*.implicit*.and*.explicit*.implementation*.provide*.safe*.way*.to*.implement*.methods*.of*.multiple*.interfaces*.by*.hiding*,*.exposing*.or*.preserving*.identities*.of*.each*.interface*.method*,*.even*.when*.the*.method*.signatures*.are*.the*.same*。
*.let's*.consider*.the*.interfaces*.defined*.below*
interface IDisposable
{
void Dispose();
}
*.here*,*.you*.can*.see*.that*.the*.class*.Student
*.has*.implicitly*.and*.explicitly*.implemented*.the*.method*.namedDispose()
*.viaDispose
*.andIDisposable.Dispose
*。
class Student : IDisposable
{
public void Dispose()
{
Console.WriteLine("Student.Dispose");
}
void IDisposable.Dispose()
{
Console.WriteLine("IDisposable.Dispose");
}
}
4.16. 什么是继承?
*.the*.ability*.of*.a*.new*.class*.to*.be*.created*,*.from*.an*.existing*.class*.by*.extending*.it*,*.is*.called*inheritance*。
public class Exception
{
}
public class IOException : Exception
{
}
*.according*.to*.the*.above*.example*,*.the*.new*.class*(IOException
*)*,*.which*.is*.called*.the*.derived*.class*.or*.subclass*,*.inherits*.the*.members*.of*.an*.existing*.class*(Exception
*)*,*.which*.is*.called*.the*.base*.class*.or*.super-class*。*.the*.classIOException
*.can*.extend*.the*.functionality*.of*.the*.classException
*.by*.adding*.new*.types*.and*.methods*.and*.by*.overriding*.existing*.ones*。
*.just*.like*.abstraction*.is*.closely*.related*.with*.generalization*,*.the*.inheritance*.is*.closely*.related*.with*.specialization*。*.it*.is*.important*.to*.discuss*.those*.two*.concepts*.together*.with*.generalization*.to*.better*.understand*.and*.to*.reduce*.the*.complexity*。
*.one*.of*.the*.most*.important*.relationships*.among*.objects*.in*.the*.real*.world*.is*.specialization*,*.which*.can*.be*.described*.as*.the*“is-a”*.relationship*。*.when*.we*.say*.that*.a*.dog*.is*.a*.mammal*,*.we*.mean*.that*.the*.dog*.is*.a*.specialized*.kind*.of*.mammal*。*.it*.has*.all*.the*.characteristics*.of*.any*.mammal*(*.it*.bears*.live*.young*,*.nurses*.with*.milk*,*.has*.hair*)*,*.but*.it*.specializes*.these*.characteristics*.to*.the*.familiar*.characteristics*.of*canis*.domesticus*。*.a*.cat*.is*.also*.a*.mammal*。*.as*.such*,*.we*.expect*.it*.to*.share*.certain*.characteristics*.with*.the*.dog*.that*.are*.generalized*.in*.Mammal*,*.but*.to*.differ*.in*.those*.characteristics*.that*.are*.specialized*.in*.cats*。
*.specialization*.and*.generalization*.relationships*.are*.both*.reciprocal*.and*.hierarchical*。*.specialization*.is*.just*.the*.other*.side*.of*.the*.generalization*.coin*:*.Mammal*.generalizes*.what*.is*.common*.between*.dogs*.and*.cats*,*.and*.dogs*.and*.cats*.specialize*.mammals*.to*.their*.own*.specific*.subtypes*。
*.similarly*,*.as*.an*.example*,*.you*.can*.say*.that*.bothIOException
*.andSecurityException
*.are*.of*.typeException
*。*.they*.have*.all*.characteristics*.and*.behaviors*.of*.an*.Exception*.that*.mean*.theIOException
*.is*.a*.specialized*.kind*.of*.Exception*。*.aSecurityException
*.is*.also*.anException
*。*.as*.such*,*.we*.expect*.it*.to*.share*.certain*.characteristics*.withIOException
*.that*.are*.generalized*.inException
*,*.but*.to*.differ*.in*.those*.characteristics*.that*.are*.specialized*.inSecurityException
s*。*.in*.other*.words*,Exception
*.generalizes*.the*.shared*.characteristics*.of*.bothIOException
*.andSecurityException
*,*.whileIOException
*.andSecurityException
*.specialize*.with*.their*.characteristics*.and*.behaviors*。
*.in*OOP*,*.the*.specialization*.relationship*.is*.implemented*.using*.the*.principle*.called*.inheritance*。*.this*.is*.the*.most*.common*.and*.most*.natural*.and*.widely*.accepted*.way*.of*.implement*.this*.relationship*。
4.17. 什么是多态?
多态*.是一个*.通用*.术语*,*.意为*“*.many*.shapes*”*。*.more*.precisely*Polymorphisms*.means*.the*.ability*.to*.request*.that*.the*.same*.operations*.be*.performed*.by*.a*.wide*.range*.of*.different*.types*.of*.things*。
*.at*.times*,*.I*.used*.to*.think*.that*.understanding*.Object*.Oriented*.Programming*.concepts*.has*.made*.it*.difficult*.since*.they*.have*.grouped*.under*.four*.main*.concepts*,*.while*.each*.concept*.is*.closely*.related*.with*.one*.another*。*.hence*,*.one*.has*.to*.be*.extremely*.careful*.to*.correctly*.understand*.each*.concept*.separately*,*.while*.understanding*.the*.way*.each*.related*.with*.other*.concepts*。
*.in*OOP*,*.the*polymorphisms*.is*.achieved*.by*.using*.many*.different*.techniques*.named*.method*.overloading*,*.operator*.overloading*.and*.method*.overriding*,
4.18. 什么是方法重载?
方法重载*.是*.*.ability*.to*.define*.several*.methods*.all*.with*.the*.same*.name*。
public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}
public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}
4.19. 什么是运算符重载?
*.operator*.overloading*(*.less*.commonly*.known*.as*.ad-hoc*polymorphisms*)*.is*.a*.specific*.case*.of*polymorphisms*.in*.which*.some*.or*.all*.of*.operators*.like*+, -*.or*.==*.are*.treated*.as*.polymorphic*.functions*.and*.as*.such*.have*.different*.behaviors*.depending*.on*.the*.types*.of*.its*.arguments*。
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}
*.in*.the*.above*.example*,*.I*.have*.overloaded*.the*.plus*.operator*.for*.adding*.two*.complex*.numbers*。*.there*.the*.two*.properties*.named*.Real*.and*.Imaginary*.have*.been*.declared*.exposing*.only*.the*.required*“get
”*.method*,*.while*.the*.object’s*.constructor*.is*.demanding*.for*.mandatory*.real*.and*.imaginary*.values*.with*.the*.user*.defined*.constructor*.of*.the*.class*。
4.20. 什么是方法重写?
方法重写*.是一种*.语言*.*.feature*.that*.allows*.a*.subclass*.to*.override*.a*.specific*.implementation*.of*.a*.method*.that*.is*.already*.provided*.by*.one*.of*.its*.super-classes*。
*.a*.subclass*.can*.give*.its*.own*.definition*.of*.methods*.but*.needs*.to*.have*.the*.same*.signature*.as*.the*.method*.in*.its*.super-class*。*.this*.means*.that*.when*.overriding*.a*.method*,*.the*.subclass's*.method*.has*.to*.have*.the*.same*.name*.and*.parameter*.list*.as*.the*.super-class's*.overridden*.method*。
using System;
public class Complex
{
private int real;
public int Real
{ get { return real; } }
private int imaginary;
public int Imaginary
{ get { return imaginary; } }
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
}
*.in*.the*.above*.example*,*.I*.have*.extended*.the*.implementation*.of*.the*.sampleComplex
*.class*.given*.under*.operator*.overloading*.section*。*.this*.class*.has*.one*.overridden*.method*.namedToString
*,*.which*.overrides*.the*.default*.implementation*.of*.the*.standardToString
*.method*.to*.support*.the*.correct*.string*.conversion*.of*.a*.complex*.number*。
Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);
// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;
// Print the numbers and the sum
// using the overridden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();
4.21. 什么是用例?
用例是*.actor*.*.perceives*.from*.the*.system*.of*.thing*。*.a*.Use*.Case*.maps*.actors*.with*.functions*。*.importantly*,*.the*.actors*.need*.not*.be*.people*。*.as*.an*.example*,*.a*.system*.can*.perform*.the*.role*.of*.an*.actor*,*.when*.it*.communicates*.with*.another*.system*。
*.in*.another*.angle*,*.a*.Use*.Case*.encodes*.a*.typical*.user*.interaction*.with*.the*.system*。*.in*.particular*,*.it*
- *.captures*.some*.user-visible*.function*。
- *.achieves*.some*.concrete*.goal*.for*.the*.user*。
*.a*.complete*.set*.of*.Use*.Cases*.largely*.defines*.the*.requirements*.for*.your*.system*:*.everything*.the*.user*.can*.see*,*.and*.would*.like*.to*.do*。*.the*.below*.diagram*.contains*.a*.set*.of*.use*.cases*.that*.describes*.a*.simple*.login*.module*.of*.a*.gaming*.website*。
4.22. 什么是类图?
*.class*.diagrams*.are*.widely*.used*.to*.describe*.the*.types*.of*.objects*.in*.a*.system*.and*.their*.relationships*。*.Class*.diagrams*.model*.class*.structure*.and*.contents*.using*.design*.elements*.such*.as*.classes*,*.packages*.and*.objects*。*.Class*.diagrams*.describe*.three*.different*.perspectives*.when*.designing*.a*.system*,*.conceptual*,*.specification*,*.and*.implementation*。*.these*.perspectives*.become*.evident*.as*.the*.diagram*.is*.created*.and*.help*.solidify*.the*.design*。
*.the*.Class*.diagrams*,*.physical*.data*.models*,*.along*.with*.the*.system*.overview*.diagram*.are*.in*.my*.opinion*,*.the*.most*.important*.diagrams*.that*.suit*.the*.current*.day*.rapid*.application*.development*.requirements*。
UML*.notations*
4.23. 什么是包图?
*.package*.diagrams*.are*.used*.to*.reflect*.the*.organization*.of*.packages*.and*.their*.elements*。*.when*.used*.to*.represent*.class*.elements*,*.package*.diagrams*.provide*.a*.visualization*.of*.the*.name-spaces*。*.in*.my*.designs*,*.I*.use*.the*.package*.diagrams*.to*.organize*.classes*.into*.different*.modules*.of*.the*.system*。
4.24. 什么是序列图?
*.sequence*.diagrams*.model*.the*.flow*.of*.logic*.within*.a*.system*.in*.a*.visual*.manner*,*.it*.enables*.both*.to*.document*.and*.validates*.your*.logic*,*.and*.are*.used*.for*.both*.analysis*.and*.design*.purposes*。*.sequence*.diagrams*.are*.the*.most*.popular*.UML*.artifact*.for*.dynamic*.modeling*,*.which*.focuses*.on*.identifying*.the*.behavior*.within*.your*.system*。
4.25. 什么是两层架构?
*.the*.two-tier*.architecture*.refers*.to*.client*/*server*.architectures*.as*.well*,*.the*.term*.client*/*server*.was*.first*.used*.in*.the*.1980s*.in*.reference*.to*.personal*.computers*(*PCs*)*.on*.a*.network*。*.the*.actual*.client*/*server*.model*.started*.gaining*.acceptance*.in*.the*.late*.1980s*,*.and*.later*.it*.was*.adapted*.to*.World*.Wide*.Web*.programming*。
*.according*.to*.the*.modern*.days*.use*.of*.two-tier*.architecture*,*.the*.user*.interfaces*(*.or*.with*.ASP.NET*,*.all*.web*.pages*)*.runs*.on*.the*.client*.and*.the*.database*.is*.stored*.on*.the*.server*。*.the*.actual*.application*.logic*.can*.run*.on*.either*.the*.client*.or*.the*.server*。*.so*.in*.this*.case*,*.the*.user*.interfaces*.are*.directly*.access*.the*.database*。*.those*.can*.also*.be*.non-interface*.processing*.engines*,*.which*.provide*.solutions*.to*.other*.remote*/*local*.systems*。*.in*.either*.case*,*.today*.the*.two-tier*.model*.is*.not*.as*.reputed*.as*.the*.three-tier*.model*。*.the*.advantage*.of*.the*.two-tier*.design*.is*.its*.simplicity*,*.but*.the*.simplicity*.comes*.with*.the*.cost*.of*.scalability*。*.the*.newer*.three-tier*.architecture*,*.which*.is*.more*.famous*,*.introduces*.a*.middle*.tier*.for*.the*.application*.logic*。
4.26. 什么是三层架构?
*.the*.three*.tier*.software*.architecture*(*.also*.known*.as*.three*.layer*.architectures*)*.emerged*.in*.the*.1990s*.to*.overcome*.the*.limitations*.of*.the*.two*.tier*.architecture*。*.this*.architecture*.has*.been*.aggressively*.customized*.and*.adopted*.by*.modern*.day*.system*.designer*.to*.web*.systems*。
*.three-tier*.is*.a*.client-server*.architecture*.in*.which*.the*.user*.interface*,*.functional*.process*.logic*,*.data*.storage*.and*.data*.access*.are*.developed*.and*.maintained*.as*.independent*.modules*,*.some*.time*.on*.separate*.platforms*。*.the*.term*“three-tier”*or*“three-layer”*,*.as*.well*.as*.the*.concept*.of*.multi-tier*.architectures*(*.often*.refers*.to*.as*.three-tier*.architecture*)*,*.seems*.to*.have*.originated*.within*.Rational*.Software*。
*.the*.three-tier*.architecture*.has*.the*.following*.three*.tiers*
- Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/ from the user
- Application Logic/ Business Logic/ Transaction Tier or Application Server: Data validation, acceptability check before being added to the database and all other business/ application specific operations
- Data Tier or Database server: Simple reading and writing method to database or any other storage, connection, command, stored procedures, etc.
4.27. What is MVC architecture?
*.the*Model-View-Controller(*MVC*)*.architecture*.separates*.the*.modeling*.of*.the*.domain*,*.the*.presentation*,*.and*.the*.actions*.based*.on*.user*.input*.into*.three*.separate*.classes*。
*.unfortunately*,*.the*.popularity*.of*.this*.pattern*.has*.resulted*.in*.a*.number*.of*.faulty*.usages*;*.each*.technology*(*Java*,*ASP.NET*,*.etc*)*.has*.defined*.it*.in*.their*.own*.way*.making*.it*.difficult*.to*.understand*。*.in*.particular*,*.the*.term*“controller”*.has*.been*.used*.to*.mean*.different*.things*.in*.different*.contexts*。*.the*.definitions*.given*.bellow*.are*.the*.closes*.possible*.ones*.I*.found*.for*.ASP.NET*.version*.of*.MVC*。
- Model: DataSet and typed DataSet (some times business object, object collection, XML, etc.) are the most common uses of the model.
- View: The ASPX and ASCX files generally handle the responsibilities of the view.
- Controllers: The handling of events or the controlling is usually done in the code-behind class.
*.in*.a*.complex*.n-tier*.distributed*.system*,*.the*.MVC*.architecture*.places*.the*.vital*.role*.of*.organizing*.the*.presentation*.tier*.of*.the*.system*。
4.28. 什么是SOA?
*.a*.service-oriented*.architecture*.is*.essentially*.a*.collection*.of*.services*。*.these*.services*.communicate*.with*.each*.other*。*.the*.communication*.can*.involve*.either*.simple*.data*.passing*.or*.it*.could*.involve*.two*.or*.more*.services*.coordinating*.some*.activity*。*.some*.means*.of*.connecting*.services*.to*.each*.other*.is*.needed*。
.NET*.Framework*.introduced*.SOA*.by*.means*.of*.web*.services*。
*.the*.SOA*.can*.be*.used*.as*.the*.concept*.to*.connect*.multiple*.systems*.to*.provide*.services*。*.it*.has*.its*.great*.share*.in*.the*.future*.of*.the*.IT*.world*。
*.according*.to*.the*.imaginary*.diagram*.above*,*.we*.can*.see*.how*.the*.Service*.Oriented*.Architecture*.is*.being*.used*.to*.provide*.a*.set*.of*.centralized*.services*.to*.the*.citizens*.of*.a*.country*。*.the*.citizens*.are*.given*.a*.unique*.identifying*.card*,*.where*.that*.card*.carries*.all*.personal*.information*.of*.each*.citizen*。*.each*.service*.centers*.such*.as*.shopping*.complex*,*.hospital*,*.station*,*.and*.factory*.are*.equipped*.with*.a*.computer*.system*.where*.that*.system*.is*.connected*.to*.a*.central*.server*,*.which*.is*.responsible*.for*.providing*.service*.to*.a*.city*。*.as*.an*.example*,*.when*.a*.customer*.enter*.the*.shopping*.complex*,*.the*.regional*.computer*.system*.reports*.it*.to*.the*.central*.server*.and*.obtains*.information*.about*.the*.customer*.before*.providing*.access*.to*.the*.premises*。*.the*.system*.welcomes*.the*.customer*。*.the*.customer*.finished*.the*.shopping*.and*.then*.by*.the*.time*.he*.leaves*.the*.shopping*.complex*,*.he*.will*.be*.asked*.to*.go*.through*.a*.billing*.process*,*.where*.the*.regional*.computer*.system*.will*.manage*.the*.process*。*.the*.payment*.will*.be*.automatically*.handled*.with*.the*.input*.details*.obtain*.from*.the*.customer*.identifying*.card*。
*.the*.regional*.system*.will*.report*.to*.the*.city*(*.computer*.system*.of*.the*.city*)*.while*.the*.city*.will*.report*.to*.the*.country*(*.computer*.system*.of*.the*.country*)*。
4.29. 什么是数据访问层?
*.the*.data*.access*.layer*(*DAL*)*,*.which*.is*.a*.key*.part*.of*.every*.n-tier*.system*,*.mainly*.consists*.of*.a*.simple*.set*.of*.code*.that*.does*.basic*.interactions*.with*.the*.database*.or*.any*.other*.storage*.device*。*.these*.functionalities*.are*.often*.referred*.to*.as*.CRUD*(*Create*,*Retrieve*,*Update*,*and*Delete*)*。
*.the*.data*.access*.layer*.need*.to*.be*.generic*,*.simple*,*.quick*.and*.efficient*.as*.much*.as*.possible*。*.it*.should*.not*.include*.complex*.application*/*business*.logics*。
*.I*.have*.seen*.systems*.with*.lengthy*,*.complex*.store*.procedures*(*SP*)*,*.which*.run*.through*.several*.cases*.before*.doing*.a*.simple*.retrieval*。*.they*.contain*.not*.only*.most*.part*.of*.the*.business*.logic*,*.but*.application*.logic*.and*.user*.interface*.logic*.as*.well*。*.if*.SP*.is*.getting*.longer*.and*.complicated*,*.then*.it*.is*.a*.good*.indication*.that*.you*.are*.burring*.your*.business*.logic*.inside*.the*.data*.access*.layer*。
4.30. 什么是业务逻辑层?
*.I*.know*.for*.a*.fact*.that*.this*.is*.a*.question*.for*.most*,*.but*.from*.the*.other*.hand*.by*.reading*.many*.articles*,*.I*.have*.become*.aware*.that*.not*.everyone*.agrees*.to*.what*.business*.logic*.actually*.is*,*.and*.in*.many*.cases*.it's*.just*.the*.bridge*.in*.between*.the*.presentation*.layer*.and*.the*.data*.access*.layer*.with*.having*.nothing*.much*,*.except*.taking*.from*.one*.and*.passing*.to*.the*.other*。*.in*.some*.other*.cases*,*.it*.is*.not*.even*.been*.well*.thought*.out*,*.they*.just*.take*.the*.leftovers*.from*.the*.presentation*.layer*.and*.the*.data*.access*.layer*.then*.put*.them*.in*.another*.layer*.which*.automatically*.is*.called*.the*.business*.logic*.layer*。*.however*,*.there*.are*.no*.god*.said*.things*.that*.cannot*.be*.changed*.in*.software*.world*。*.you*.can*.change*.as*.and*.when*.you*.feel*.comfortable*.that*.the*.method*.you*.apply*.is*.flexible*.enough*.to*.support*.the*.growth*.of*.your*.system*。*.there*.are*.many*.great*.ways*,*.but*.be*.careful*.when*.selecting*.them*,*.they*.can*.over*_.complicating*_.the*.simple*.system*。*.it*.is*.a*.balance*.one*.needs*.to*.find*.with*.one's*.experience*。
*.as*.a*.general*.advice*,*.when*.you*.define*.business*.entities*,*.you*.must*.decide*.how*.to*.map*.the*.data*.in*.your*.tables*.to*.correctly*.defined*.business*.entities*。*.the*.business*.entities*.should*.meaningfully*.define*.considering*.various*.types*.of*.requirements*.and*.functioning*.of*.your*.system*。*.it*.is*.recommended*.to*.identify*.the*.business*.entities*.to*.encapsulate*.the*.functional*/*UI*(*User*.Interface*)*.requirements*.of*.your*.application*,*.rather*.than*.define*.a*.separate*.business*.entity*.for*.each*.table*.of*.your*.database*。*.for*.example*,*.if*.you*.want*.to*.combine*.data*.from*.couple*.of*.tables*.to*.build*.a*.UI*(*User*.Interface*)*.control*(*Web*.Control*)*,*.implement*.that*.function*.in*.the*.Business*.Logic*.Layer*.with*.a*.business*.object*.that*.uses*.couple*.of*.data*.object*.to*.support*.with*.your*.complex*.business*.requirement*。
4.31. 什么是四人帮(GoF)设计模式?
*.the*.Gang*.of*.Four*(*GoF*)*.patterns*.are*.generally*.considered*.the*.foundation*.for*.all*.other*.patterns*。*.they*.are*.categorized*.in*.three*.groups*:*.Creational*,*.Structural*,*.and*.Behavioral*。*.here*,*.you*.will*.find*.information*.on*.these*.important*.patterns*。
Creational Patterns
- Abstract Factory - creates an instance of several families of classes
- Builder - separates object construction from its representation
- Factory method - creates an instance of several derived classes
- Prototype - A fully initialized instance to be copied or cloned
- Singleton - A class of which only a single instance can exist
Structural Patterns
- Adapter - match interfaces of different classes
- Bridge - separates an object’s interface from its implementation
- Composite - a tree structure of simple and composite objects
- Decorator - adds responsibilities to objects dynamically
- Facade - a single class that represents an entire subsystem
- Flyweight - a fine-grained instance used for efficient sharing
- Proxy - an object representing another object
Behavioral Patterns
- Chain of resp - a way of passing a request between a chain of objects
- Command - encapsulate a command request as an object
- Interpreter - a way to include language elements in a program
- Iterator - sequentially access the elements of a collection
- Mediator - defines simplified communication between classes
- Memento - captures and restores an object's internal state
- Observer - a way of notifying change to a number of classes
- State - alter an object's behavior when its state changes
- Strategy - encapsulates an algorithm inside a class
- Template method - defers the exact steps of an algorithm to a subclass
- Visitor - defines a new operation to a class without change
4.32. 抽象工厂和生成器设计模式之间有什么区别?
*.the*.two*.design*.patterns*.are*.fundamentally*.different*。*.however*,*.when*.you*.learn*.them*.for*.the*.first*.time*,*.you*.will*.see*.a*.confusing*.similarity*。*.so*.that*.will*.make*.it*.harder*.for*.you*.to*.understand*.them*。*.but*.if*.you*.continue*.to*.study*.eventually*,*.you*.will*.get*.afraid*.of*.design*.patterns*.too*。*.it*.is*.like*.infant*.phobia*,*.once*.you*.get*.afraid*.at*.your*.early*.age*,*.it*.stays*.with*.you*.forever*。*.so*.the*.result*.would*.be*.that*.you*.never*.look*.back*.at*.design*.patterns*.again*。*.let*.me*.see*.whether*.I*.can*.solve*.this*.brain*.teaser*.for*.you*。
*.in*.the*.image*.below*,*.you*.have*.both*.design*.pattern*.listed*.in*。*.I*.am*.trying*.to*.compare*.the*.two*.one*.on*.one*.to*.identify*.the*.similarities*。*.if*.you*.observe*.the*.figure*.carefully*,*.you*.will*.see*.an*.easily*.understandable*.color*.pattern*(*.same*.color*.is*.used*.to*.mark*.the*.classes*.that*.are*.of*.similar*.kind*)*。
*.please*.follow*.up*.with*.the*.numbers*.in*.the*.image*.when*.reading*.the*.listing*.below*
- Mark#1: Both patterns have used a generic class as the entry-class. The only difference is the name of the class. One pattern has named it as “
Client
”, while the other named it as “Director
”. - Mark#2: Here again, the difference is the class name. It is “
AbstractFactory
” for one and “Builder
” for the other. Additionally, both classes are of typeabstract
. - Mark#3: Once again, both patterns have defined two generic (
WindowsFactory
andConcreteBuilder
) classes. They both have created by inheriting their respectiveabstract
class. - Mark#4: Finally, both seem to produce some kind of a generic output.
*.now*,*.where*.are*.we*?*.aren’t*.they*.looking*.almost*.identical*?*.so*.then*,*.why*.are*.we*.having*.two*.different*.patterns*.here*?
*.let's*.compare*.the*.two*.again*.side*.by*.side*.for*.one*.last*.time*,*.but*.this*.time*,*.focusing*.on*.the*.differences*。
- Abstract Factory: Emphasizes a family of product objects (either simple or complex)
- Builder: Focuses on constructing a complex object step by step
- Abstract Factory: Focus on *what* is made
- Builder: Focus on *how* it is made
- Abstract Factory: Focus on defining many different types of *factories* to build many *products*, and it is not a one builder for just one product
- Builder: Focus on building a one complex but one single *product*
- Abstract Factory: Defers the choice of what concrete type of object to make until run time
- Builder: Hide the logic/ operation of how to compile that complex object
- Abstract Factory: *Every* method call creates and returns different objects
- Builder: Only the *last* method call returns the object, while other calls partially build the object
*.sometimes*.creational*.patterns*.are*.complementary*:*.so*.you*.can*.join*.one*.or*.many*.patterns*.when*.you*.design*.your*.system*。*.as*.an*.example*.builder*.can*.use*.one*.of*.the*.other*.patterns*.to*.implement*.which*.components*.get*.built*.or*.in*.another*.case*.Abstract*.Factory*,*.Builder*,*.and*.Prototype*.can*.use*.Singleton*.in*.their*.implementations*。*.so*.the*.conclusion*.would*.be*.that*.the*.two*.design*.patterns*.exist*.to*.resolve*.two*.type*.of*.business*.problems*,*.so*.even*.though*.they*.look*.similar*,*.they*.are*.not*。
*.I*.hope*.that*.this*.shed*.some*.light*.to*.resolve*.the*.puzzle*。*.if*.you*.still*.don’t*.understand*.it*,*.then*.this*.time*.it*.is*.not*.you*,*.it*.has*.to*.be*.me*.and*.it*.is*.since*.that*.I*.don’t*.know*.how*.to*.explain*.it*。
5. 结论是什么?
*.I*.don't*.think*.that*.it*.is*.realistic*.trying*.to*.make*.a*.programming*.language*.be*.everything*.to*.everybody*。*.the*.language*.becomes*.bloated*,*.hard*.to*.learn*,*.and*.hard*.to*.read*.if*.everything*.plus*.the*.kitchen*.sink*.is*.thrown*.in*。*.in*.other*.words*,*.every*.language*.has*.its*.limitations*。*.as*.system*.architect*.and*.designer*,*.we*.should*.be*.able*.to*.fully*.and*.more*.importantly*.correctly*(*.this*.also*.means*.that*.you*.shouldn’t*.use*.a*.ballistic*.missile*.to*.kill*.a*.fly*.or*.hire*.FBI*.to*.catch*.the*.fly*)*.utilize*.the*.available*.tools*.and*.features*.to*.build*.usable*,*.sustainable*,*.maintainable*.and*.also*.very*.importantly*.expandable*.software*.systems*,*.that*.fully*.utilize*.the*.feature*.of*.the*.language*.to*.bring*.a*.competitively*.advance*.system*.to*.their*.customers*。*.in*.order*.to*.do*.it*,*.the*.foundation*.of*.a*.system*.places*.a*.vital*.role*。*.the*.design*.or*.the*.architecture*.of*.a*.software*.system*.is*the*.foundation*。*.it*.holds*.the*.system*.together*,*.hence*.designing*.a*.system*.properly*(*.this*.never*.mean*.an*over*-designing*)*.is*.the*.key*.to*.the*.success*。*.when*.you*.talk*.about*.designing*.a*.software*.system*,*.the*.correct*.handling*.of*.OOP*.concept*.is*.very*.important*。*.I*.have*.made*.the*.above*.article*.richer*.with*.idea*.but*.still*.kept*.it*.short*.so*.that*.one*.can*.learn*/*remind*.all*.of*.important*.concept*.at*.a*.glance*。*.hope*.you*.all*.will*.enjoy*.reading*.it*。
What Next?
*.it*.is*.good*.to*.learn*.all*.these*.theories*,*.but*.one*.can*.ask*.the*.point*.of*.learning*.them*.if*.you*.don't*.know*.how*.to*.put*.them*.into*.practise*。*.these*.need*.to*.give*.us*.some*.benefits*,*.right*?*.therefore*,*.I*.thought*.that*.I*.should*.demonstrate*.the*.use*.of*.these*.concepts*.at*.least*.in*.one*.concrete*.project*。
*.therefore*,*.a*.team*.of*.us*.developed*.a*.framework*.called*'Nido'*Framework*。*.this*.virtually*.demonstrates*.the*.use*.of*.most*.of*.these*.OOP*.concepts*。
*.it*.is*.very*.popular*.among*.developers*.these*.days*。*.Nido*.Framework*.is*.a*.reusable*,*.highly*.generic*.code*.library*.developed*.using*.Microsoft*.NET*/*C#*.to*.provide*.a*.common*.platform*.for*.all*.NET*.systems*。*.you*.can*.derive*.your*.project*.from*.Nido*.and*.quickly*.develop*.your*.systems*。
*.if*.you*.want*.to*.beat*.your*.colleague*.with*.your*.coding*.speed*.or*.want*.to*.meet*.those*.tough*.deadlines*.which*.you*.always*.failed*.to*.hit*,*.try*.using*.Nido*。*.today*,*.most*.the*.university*.students*.and*.professionals*.use*.Nido*.for*.their*.development*.and*.share*.their*.success*.stories*。
*.we*.have*.tested*.it*.with*.a*.number*.of*.complex*.business*.applications*.where*.it*.has*.proved*.to*.deliver*.stable*,*.robust*.system*.at*.an*.extremely*.short*.time*.frame*。*.if*.you*.want*.to*.check*.Nido*.source*.code*.or*.learn*.the*.architecture*,*.please*.visit*.the*.links*.given*.below*。*.by*.the*.way*,*.it*.is*.open*.source*.and*.free*.to*.use*.in*.commercial*.projects*。
- ASP.NET/C# Development with Nido Framework for Dummies
- Nido Framework @ CodePlex.com
- Download Nido @ NuGet
- Gain Coding Speed with Nido (FREE) Framework .NET/ C#
6. 我参考了什么?
- MSDN: http://msdn2.microsoft.com/en-us/library/default.aspx
- Practical Approach to Computer Systems Design and Architecture: https://codeproject.org.cn/useritems/System_Design.asp
- Introduction: What is Object-Oriented Programming?: http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html
- Basic Object-Oriented Concepts: http://www.toa.com/pub/oobasics/oobasics.htm
- Inheritance and Polymorphism—Specialization and Generalization: http://en.csharp-online.net/Inheritance_and_Polymorphism%E2%80%94Specialization_and_Generalization
- Abstraction and Generalization: http://cs.wwc.edu/~aabyan/PLBook/HTML/AbsGen.html
- Object Oriented Analysis and Design Team: http://atlas.kennesaw.edu/~dbraun/csis4650/A&D/index.htm
- Client/Server Software Architectures--An Overview: http://www.sei.cmu.edu/str/descriptions/clientserver.html
- Service-oriented architecture (SOA) definition: http://www.service-architecture.com/web-services/articles/service-oriented_architecture_soa_definition.html
- http://www.dofactory.com/Patterns/Patterns.aspx
- http://www.objectmentor.com
- Builder Design Pattern [Wiki]
7. History
- 28 January, 2008
- Added more content base on design principles
- Added History section
- 4 February, 2008
- Added more details to explain the Composition
- 15 April, 2008
- Added comparison between Abstract Factory and Builder
- Updated some of the wording slightly
- 31 May, 2010
- - Corrected the 'Composition' related description, as pointed here
- 26 January, 2011
- Conclusion is updated and a link is added to Rocket-Framework
- 23 October, 2014
- Added 'What Next' Section
- 27 January, 2015
- Special thanks goes toJason Forbes, KP Lee andTamer (Member 11378393) for their contributions to make some important corrections