简体   繁体   中英

Is it better to use interface or an abstract class in this situation?

I want to know, If I have a shopping(eg the cart..payment process) class and I want to add the possibility to pay via paypal..is better to use an abstract class Docs or an interface Docs , eg:

Shopping implements Visa,Paypal

I guess that interface is the right answer, since the Shopping class will be recommended to be an abstract class?

Neither.

Shopping (if you say its the main system, eg the shopping cart) should have a list of providers that implement/inherit PaymentProcessor . Visa and PayPal would implement/inherit from PaymentProcessor .

That way you can inject via some configuration what PaymentProcessor s are available. That way Shopping won't have to change if you add MasterCard .

Have a look at the single responsibility principle .

Just based off of the name of your class I would guess you should use neither. The pattern you should look at is called composition. See http://en.wikipedia.org/wiki/Object_composition .

In short, your shopping class "uses a" payment processor, is isn't one itself (ie not an "is a" relationship)

I'd implement your shopping class to accept a payment processor either when it is instantiated or via a set method on the object.

You may also want to read up on design patterns , particularly from the Gang of Four.

None of it, I would say. It would be better to have a Class for each paying method. I would use an abstract Class Paying (or similar) which implements aspects all paying methods use. Then you could write an Interface for every method (not really necessary) and the real implementation of every method that extends Paying (and might implement Visa ).

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