抽象和封装是两种口味很好的味道.
封装可以最大限度地减少您向代码用户公开的内容."用户"可能是您的代码的其余部分,也可能是使用您发布的代码的任何人.
封装有一些明确的好处:
我不懂Java,但这里有一个C#封装的小例子:
public class Giraffe
{
public Giraffe(int heightInFeet)
{
this.heightInFeet = heightInFeet;
this.numberOfSpots = heightInFeet * 72;
}
public override string ToString()
{
return "Height: " + heightInFeet + " feet"
+ " Number of Spots: " + numberOfSpots;
}
private int heightInFeet;
private int numberOfSpots;
}
Run Code Online (Sandbox Code Playgroud)
它不是暴露numberOfSpots,而是封装在类中,并通过该ToString方法公开.
抽象是使用扩展点让选择被推迟到运行精确代码的不同部分.该选择可以在程序的其他地方,在另一个程序中进行,也可以在运行时动态进行.
抽象也有很多好处:
C#中一个高度使用的抽象是IEnumerable.列表,数组,字典和任何其他类型的集合类都实现IEnumerable.的foreach环结构和LINQ库的整体是基于抽象:
public IEnumerable<int> GetSomeCollection()
{
// This could return any type of int collection. Here it returns an array
return new int[] { 5, 12, 7, 14, 2, 3, 7, 99 };
}
IEnumerable<int> someCollectionOfInts = GetSomeCollection();
IEnumerable<string> itemsLessThanFive = from i in someCollectionOfInts
where i < 5
select i.ToString();
foreach(string item in itemsLessThanFive)
{
Console.WriteLine(item);
}
Run Code Online (Sandbox Code Playgroud)
您也可以轻松编写自己的抽象:
public interface IAnimal
{
bool IsHealthy { get; }
void Eat(IAnimal otherAnimal);
}
public class Lion : IAnimal
{
public Lion()
{
this.isHealthy = true;
}
public bool IsHealthy
{
get { return isHealthy; }
}
void Eat(IAnimal otherAnimal)
{
if(otherAnimal.IsHealthy && !(otherAnimal is SlimeMold))
{
isHealthy = true;
}
else
{
isHealthy = false;
}
}
private bool isHealthy;
}
IAnimal someAnimal = PullAnAnimalOutOfAWoodenCrate();
Console.WriteLine("The animal is healthy?: " + someAnimal.IsHealthy);
Run Code Online (Sandbox Code Playgroud)
你可以像我一样使用它们IAnimal,和IsHealthy. IAnimal是一个缩写,只有一个get访问器,没有set访问器IsHealthy是封装.
这两个概念完全不同.
抽象是使基类"抽象"然后扩展其功能的实践.抽象类是具体事物中不存在的东西; 它的唯一目的是扩展.想想你是否在编写代表不同物种的课程.你所有不同的物种都可以延伸一个抽象的动物类,因为它们都会像动物一样拥有共同的属性.但是,你永远不会实例化一个动物对象,因为你在世界上看到的每一只动物都是松鼠,狗,或鱼......或某种基础的抽象动物类的具体实现.
封装是将类变量设为私有,然后允许从get和set方法访问它们的做法.这样做的目的是分开访问数据的方式和实现方式.例如,如果您有一个有需求的变量,那么每次更改它时,它也会将第二个变量递增1,然后您将封装该功能; 这样你的代码就更可靠,因为每次访问原始变量时都不必记住遵守该规则.
如果您需要特定的代码示例,我建议您只进行谷歌搜索,因为有很多可用的示例.这是两个:
http://www.tutorialspoint.com/java/java_abstraction.htm http://www.tutorialspoint.com/java/java_encapsulation.htm
| 归档时间: |
|
| 查看次数: |
39039 次 |
| 最近记录: |