本文介绍了这是一个众所周知的设计模式吗?它叫什么名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在代码中看到这个,但是当我说出来的时候,我不知道这种模式的名称。



我有一个方法2调用一个重载方法的参数,它有3个参数,并有意将第3个参数设置为空字符串。

  public void DoWork(string name ,string phoneNumber)
{
DoWork(name,phoneNumber,string.Empty)
}

private void DoWork(string name,string phoneNumber,string emailAddress)
{
//做工作
}

这样做是不要重复代码,并允许现有的呼叫者仍然调用只有2个参数的方法。



这是一个模式,它是否有一个名字?

解决方案

实际上不仅仅是方法重载(其中通常同样的方法名称不同的参数类型),这个具体的模式 - 基本上是重载相同的方法,较短的一个调用较长的一个具有默认值来模拟可选参数 - 称为伸缩/伸缩模式,通常在构造函数上看到,但当然可以归因于任何方法。






有关更具权威性的报价,请参阅有效Java第2版项目2:考虑构建器模式当面对许多构造函数参数()

再次,通常在构造函数的上下文(例如,一个2-arg构造函数将有一行这个(arg1,arg2,ARG3_DEFAULT); 来调用3-arg构造函数等),但是我不明白为什么不能将其推广到其他方法。






另一个权威报价,不幸的是没有定义模式: a href =http://java.sun.com/j2se/javadoc/writingdoccomments/ =noreferrer> Sun开发人员网络:如何为Javadoc工具撰写文档评论:






另一个随机报价,更明确的定义模式::

引用直接提出,默认参数的语言支持是一个更好的选择。


I have seen this often in code, but when I speak of it I don't know the name for such 'pattern'

I have a method with 2 arguments that calls an overloaded method that has 3 arguments and intentionally sets the 3rd one to empty string.

public void DoWork(string name, string phoneNumber)
{
    DoWork(name, phoneNumber, string.Empty)
}

private void DoWork(string name, string phoneNumber, string emailAddress)
{
    //do the work
}

The reason I'm doing this is to not duplicate code, and to allow existing callers to still call the method that has only 2 parameters.

Is this a pattern, and does it have a name?

解决方案

It's actually more than just method overloading (where usually the same method name has different argument types), this specific pattern -- where overloads are basically the same method, and the shorter one invokes the longer one with default value to emulate optional parameters -- is called the telescopic/telescoping pattern, usually seen on constructors, but of course generalizable to any method.


For a more authoritative quote, here's an excerpt from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters (excerpt online)

Again, usually the telescopic pattern is discussed within the context of constructors (where e.g. a 2-arg constructor would have one line this(arg1, arg2, ARG3_DEFAULT); to invoke the 3-arg constructor, etc), but I don't see why it can't be generalized to other methods as well.


Another authoritative quote, unfortunately with no definition of the pattern: Sun Developer Network: How to Write Doc Comments for the Javadoc Tool:


And another random quote, with a more explicit definition of the pattern: I Am Hate Method Overloading (And So Can You!):

This last quote directly proposes that language support for default arguments is a much better alternative.

这篇关于这是一个众所周知的设计模式吗?它叫什么名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:27