简体   繁体   中英

Inheritance Base class with one instance

I want to know if it's possible having something like this:

  • basic class A1
  • derived class A2 : A1
  • derived class A3 : A1

to have only one instance of A1? Because when I use ctor(params):base(params) for each derived class A2 , A3 create a new instance of A1 and I want to avoid this.

Via inheritance, no. This isn't possible. If you chose composition though, this can be accomplished.

A1 becomes a Singleton.

A2 and A3 both have a reference to the Singleton instance of A1 and proxies the appropriate calls through to that instance.

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