代码之家  ›  专栏  ›  技术社区  ›  James Raitsev

Java中的简单继承

  •  2
  • James Raitsev  · 技术社区  · 15 年前

    假设您需要实现一个业务函数,它设置了某种概要文件。

    但是,根据接收数据的方式,设置配置文件将以不同的方式实现。

    例如,参数可以直接传递给对象,对象可以

    setProfile();
    

    或者,参数必须被发现,并且必须通过

    setProfile(String[] data, Blah blooh);
    

    在这种情况下,最好的方法是什么?我的意思是,从设计上讲,你会如何设计这个?

    我在考虑使用一个抽象方法的接口,这是可行的,但引入了一些噪声。不太确定如何最好地构造这个。

    3 回复  |  直到 7 年前
        1
  •  3
  •   Esko    15 年前

    我将通过将实际的概要文件抽象到它自己的类层次结构来封装它并将泛型添加到 setProfile() . 当然,它确实增加了一些复杂性,但是因为它也引入了间接性,所以代码将更加解耦,从长远来看,这应该是有用的。

    此外,实际的函数可以完全在自己的类层次结构中,以使该部分也可插入,这意味着 Strategy Pattern 在你手中。然而,应用这一点的决定需要对正在构建的系统有更多的了解,并且可能不适合您正在构建的系统。

    快速实例:

    /**
     * Interface for describing the actual function. May (and most likely does)
     * contain other methods too.
     */
    public interface BusinessFunction<P extends Profile> {
        public void setProfile(P p);
    }
    

    /**
     * Base profile interface, contains all common profile related methods.
     */
    public interface Profile {}
    

    /**
     * This interface is mostly a matter of taste, I added this just to show the 
     * extendability.
     */
    public interface SimpleProfile extends Profile {}
    

    /**
     * This would be what you're interested of.
     */
    public interface ComplexProfile extends Profile {
        String[] getData();
        Blah blooh();
    }
    

    /**
     * Actual function.
     */
    public class ComplexBusinessFunction implements BusinessFunction<ComplexProfile> {
        public void setProfile(ComplexProfile p) {
            // do whatever with p which has getData() and blooh()
        }
    }
    

    /**
     * And another example just to be thorough.
     */
    public class SimpleBusinessFunction implements BusinessFunction<SimpleProfile> {
        public void setProfile(SimpleProfile p) {
            // do whatever with the empty profile
        }
    }
    
        2
  •  5
  •   kbrimington    15 年前

    我总是对有很多重载的方法感到紧张。在本例中,我更喜欢将方法参数视为消息,而不是参数,并构建一个这样的方法:

    setProfile(ProfileData data)
    

    这个 ProfileData 类可以包含所有 setProfile 方法,您可以为专门化创建派生类 设置轮廓 操作。

    如果您使用的序列化技术可以自动保持 轮廓线 基于其结构的对象。

        3
  •  0
  •   JonWillis    15 年前

    对于get/set方法,我总是将set方法作为单个输入。可能是一个简单的对象,也可能是一个更复杂的对象,如Kbirmington所建议的。我认为我这样做更多是出于一贯的设计优势。

    值得记住的是,如果配置文件数据有10个属性,而它们只提供了9个属性,那么就可能有9种不同的方法需要根据实际缺少的10个属性中的哪一个来编写。

    至少对于一个结构,有一个输入,而且如果结构改变了,方法不仅仅是其中的代码。

    在这方面,您正在编程到一个接口,这是一个很好的设计范例。