What's the difference between an abstract class and a static one?

后端 未结 9 1907
臣服心动
臣服心动 2020-12-02 18:55

Neither is instantiable. What are the differences, and in what situations might you use one or the other?

9条回答
  •  离开以前
    2020-12-02 19:03

    Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.

    Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:

    abstract class Authenticator {
    
       protected Dictionary userCache;
    
       ...
    
       public User LoadUser(string name) {
            User user;
            if( userCache.TryGet(name, out user) ) return user;
            else {
                user = LoadFromStore(name);
                userCache.Add(name, user);
                return user;
            }
       }
    
       protected abstract User LoadFromStore(string name);
    }
    

    Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.

    Static class are a different matter alltogether. They are essentially a place to keep your utility functions:

    static class StrUtil {
    
        public static string TrimWhitespace(string str) {
            ...
        }
    }
    

    Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.

提交回复
热议问题