Generic base class wraps nested generic class to reduce type argument specification: Is there a name for this pattern?

前端 未结 3 1219
臣服心动
臣服心动 2021-01-15 19:41

Ok question title is far from being self-explanatory. I see myself doing this often:

From this answer:

public static class Equality
{
    pu         


        
相关标签:
3条回答
  • 2021-01-15 20:24

    I think this is a lot like Class Clusters pattern which is based on Abstract Factory pattern.

    0 讨论(0)
  • 2021-01-15 20:32

    As rightly pointed out by Bertie, I might have not followed any one pattern here.

    I would say that by delegating the instantiation of concrete implementation to CreateComparer method, I have just simplified the object creation - which comes under Creation Method patterns. By having a static function for object instantiation, it was sort of a factory pattern - specifically this variant of Factory Method.

    By inheriting Impl from Equater I have sort of followed the Abstract Factory pattern - where Equater is factory of factory and Impl is its implementation to give Impl itself back, except that Impl is really not creating any other object (in other words Impl is not meant to be a factory), but getting instantiated itself via constructor. So in strict sense, its not Abstract Factory pattern, but it will be closer to if Impl can have a method to call the constructor of itself and return back an instance.

    Also by embedding and hiding the implementation detail (the nested classes as such), the exposed class (parent class) fakes to outside world as if it is doing it's job. It's what is called Delegation Pattern

    As far as a name for hiding implementation of a generic class in a nested generic class to give easier signature for method calls is concerned I don't think there exist one. Even if any name existed, it has to be very specific to the language (or similar languages) since language constructs like generics/type inference etc are involved. Eric Lippert finds the same use in nested classes here although its not generics related, where he calls it Factory pattern.

    0 讨论(0)
  • 2021-01-15 20:43

    I don't think you've followed any one pattern here.

    I would say that by replacing multiple "CreateComparer" methods with a single "Create" method, you have just simplified a Creation Method pattern. You could in a sense say it was a sort of a Factory pattern?! Or maybe a Builder pattern - that one is open to interpretation I guess?!

    By embedding "Impl" within "Equater" you have sort of followed the Command pattern - encapsulating method invocation so that your calling code doesn't know about how it's getting done.

    Anyway, sorry I can't be more helpful than that or give you a definite answer! Anyway, hope it helps!

    0 讨论(0)
提交回复
热议问题