0
点赞
收藏
分享

微信扫一扫

第1篇:计算机网络概述与基础

倪雅各 2024-10-30 阅读 12

在开发中我们会遇到需要从同一个对象中获取多个值的情况,例如从对象rectangle 中获取长方形的宽width和高height,然后将这个两个值传递给方法GetArea去计算面积:

public class Demo
{
	public void Method()
	{
		//---------------
		//more code
		//---------------
		
		float width=rectangle_a.Width;
		float height=rectangle_a.Height;
		float are_a=GetArea(width,height);
		
		//-------------------
		//more code
		//------------------

		float width=rectangle_b.Width;
		float height=rectangle_b.Height;
		float are_b=GetArea(width,height);

		//------------------
		//more code
		//-----------------
	}
	private float GetArea(float width,float height)
	{
		return width*height;
	}
}

这种方式看起来很简单,但是存在一个问题,如果rectangle对象的内部不再通过属性的方式来获取去widthheight,而是通过方法的形式来获取,或者需要再增加获取一个属性 Color 传递个GetArea 方法,那么我们就要大量的修改代码了(前述代码我们要修改两个地方)。那么,要解决这个问题,我们可以将整个对象传递给要调用的方法,让要掉用的方法内部去负责获取这些属性。以下是修改后的代码:

public class Demo
{
	public void Method()
	{
		//---------------
		//more code
		//---------------
		
		float are_a=GetArea(rectangle_a);
		
		//-------------------
		//more code
		//------------------
		
		float are_b=GetArea(rectangle_b);

		//------------------
		//more code
		//-----------------
	}
	private float GetArea(Rectangle rectangle)
	{	
		return rectangle.Width*rectangle.Height;
	}
}

“保留整个对象” 这种重构方式的优点是我们看到的不再是一大堆参数,而是一个具有易懂名称的单一对象。并且如果方法需要从对象中获取非常多的数据,那么无需重写所有使用该方法的地方,只需要在方法内部重写就可以了。缺点也是显而易见的,在某些情况下这种转换会导致方法的灵活性降低,原本可以从许多不同的来源获取数据,但是由于重构,我们只能将其用于具有特定类型的对象。

举报

相关推荐

0 条评论