简体   繁体   中英

Looking for an interface/abstract but with methods returning different types

I am looking for a design pattern for a base class that forces all derived classes to implement all base class methods, while the methods in the derived classes have different return types. The scenario is a generic MemoryObject class (interface/abstract), keeping and returning whatever kind of objects in/from memory. But the derived classes (static/sealed/singleton) should return the correct type.

So the requirements are - force all derived classes to implement all properties and methods of the base class - methods in derived classes must return correct type

Here's some sample code, not compilable, but for illustration:

    public interface MemoryObject
    {
         object FromMemory { get; }
         //... other properties and methods
    }

    public sealed class MemoryObjectA : MemoryObject
    {
        public static List<string> FromMemory 
        {
            get { return new List<string>(); }
        }

        //... other properties and methods
    }

    public sealed class MemoryObjectB : MemoryObject
    {
        public static DataTable FromMemory 
        {
            get { return new DataTable(); }
        }

        //... other properties and methods
    }

Thanks for your suggestions in advance!

It sounds like you just need to make it generic:

public interface MemoryObject<T>
{
     T FromMemory { get; }
     //... other properties and methods
}

public class MemoryObjectA : MemoryObject<List<string>> { ... }
public class MemoryObjectB : MemoryObject<DataTable> { ... }

Note that the implementation methods will have to be instance methods, not static methods. (You can make the implementations singletons though, should you wish.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM