Why are decorator design patterns always shown as classes and subclasses in examples? - decorator

For example, in freecodecamp.org, an example of running a coffee shop is used:
public abstract class Beverage {
private String description;
public Beverage(String description) {
super();
this.description = description;
}
public String getDescription() {
return description;
}
public abstract double cost();
}
They then use subclasses for all the various add-ons such as various roasts and items like sugar/milk:
public abstract class AddOn extends Beverage {
protected Beverage beverage;
public AddOn(String description, Beverage bev) {
super(description);
this.beverage = bev;
}
public abstract String getDescription();
}
And they follow up with a couple subclasses of AddOn:
public class Sugar extends AddOn {
public Sugar(Beverage bev) {
super(“Sugar”, bev);
}
#Override
public String getDescription() {
return beverage.getDescription() + “ with Mocha”;
}
#Override
public double cost() {
return beverage.cost() + 50;
}
}
public class Milk extends AddOn {
public Milk(Beverage bev) {
super(“Milk”, bev);
}
#Override
public String getDescription() {
return beverage.getDescription() + “ with Milk”;
}
#Override public double cost() {
return beverage.cost() + 100;
}
}
What I don't get is, why is everything a subclass, rather than just having everything as a method in Beverage that adds to one big description and adds to a universal cost?

You're right that for these very simple examples one big class might well be better. However, in actual code an individual decorator may well have a lot of code to do its decoration. The Single Responsiblity Principle then applies. We don't want to create a big God class that does lots of things, we want to break things up and modularize somehow. In particular we don't want to always change the same class when we want to change how things work. Decorators allow us to modularize and extend whilst retaining polymorphism and a lot of flexibility about objects we are creating.
Having said that, whilst decorators are one of the original Gang of Four design patterns, you don't see them much in the real world. You can easily end up with a lot of confusing small classes that don't do a lot. So you have a point, and the pattern is a useful tool in the toolbox but maybe one you won't get out too often.

Related

any work around to allow for an action result to accept a Abstract class as parameter

I have different configurations all inheriting from a base configuration that are customized in forms. I want all of these to be handled by a single action result.
[HttpPost]
public IActionResult Register(AbstractBaseConfig config)
{
...do some logic...
return View("../Home/Index");
}
However, this is not possible because you cannot base in abstract classes as a parameter to an action result. Is there any work around for this so I don't need a seperate action result for each configuration? (I still want each configuration to be it's own class, I only need access to the base class methods in the action result logic).
Basically you can't, and the reason is that MVC will try to do new AbstractBaseConfig() as part of the Data Binding process (which parses the URL or the Form Post and puts the results in a concrete object). And by definition, doing new AbstractBaseConfig() is impossible for an abstract class.
It also makes sense for other reasons, I will explain why.
You seem to expect that MVC can determine the class from the parameters that are being passed in. That is not how it works, in fact the opposite is true: the Action Method has to specify the exact class, and then the Binder will instantiate that exact class and try to bind its properties.
Suppose you had this:
public abstract class Thing { public int ID { get;set; } }
public class NamedThing : Thing { public string Name { get;set; } }
public class OtherThing : Thing { public string Name { get;set; } }
and suppose it would be allowed to use:
public IActionResult Register(Thing thing)
then what would you expect to be in thing after Data Binding: a Thing object with only the ID set? Or one of the other object types, with Name set, but how would MVC ever be able to know which class you meant?
So for all these reasons, this is not possible.
You could have a base class inherit the abstract class and all your classes inherit from that base class whilst having that base class as your parameter
Take for example
public abstract class ABase
{
public void stuff()
{
var stuff = string.Empty;
stuff = "hello";
}
public virtual void otherstuff()
{
var stuff = string.Empty;
stuff = "hello";
}
}
public class Base : ABase
{
//empty
}
public class Derived : Base
{
public void mystuff()
{
this.stuff();
}
public override void otherstuff()
{
// Custom code
}
}
public ActionResult Register(Base config)
{
}

Combining two identical sub classes

So I have two sub classes that extend different base classes in Flex how can I combine these so that I am not repeating myself.
Basically I have something like
public class A extends B {
// methods
}
public class C extends D {
// same methods as class A
}
any way to combine this so that I am not repeating the same code twice.
Favor composition over inheritance
So, the question is, how should you compose the solution?
One possibility is to use Decorator pattern. This is essentially a wrapper around your existing Classes. To make this work, your Classes will probably need to implement an Interface that exposes whatever you'll need to do the job.
So something like:
public interface IFoo {
function get name():String;
function set name(value:String):void;
}
public class A extends B implements IFoo {
protected var _name:String;
public function get name():String {
return _name;
}
public function set name(value:String):void {
_name = value;
}
}
public class C extends D implements IFoo {
protected var _name:String;
public function get name():String {
return _name;
}
public function set name(value:String):void {
if (_value != _name) {
_name = value;
dispatchEvent(new Event('nameChanged'));
}
}
}
public class FooDecorator {
protected var _foo:IFoo;
public function FooDecorator(foo:IFoo) {
_foo = foo;
}
public function sayName():void {
trace('foo name is', _foo.name);
}
}
Another solution is to give both A and C member variables of a fifth type that encapsulate the behavior (like what Jeffry said, but I prefer to obey the law of Demeter where possible):
class NameSayer {
function sayName(name:String):void {
trace('foo name is', _foo.name);
}
}
then
public class A extends B {
public var name:String;
public var sayer:NameSayer;
//note that this method would be identical in both Classes
//but this is OK because the underlying logic is encapsulated
//and can be easily changed
public function sayName():void {
if (sayer) {
sayer.sayName();
}
}
}
I think many developers get too hung up on zealously following DRY and, as Jeffry says, this can cause other, worse, problems in your architecture. Which, if any, of these solutions is appropriate will depend on exactly what you're trying to accomplish.
You have two child classes (extending different parents) that implement the exact same methods.
public class B {}
public class D {}
public class A extends B {
// methods
m1();
m2();
...
}
public class C extends D {
// same methods as class A
m1();
m2();
...
}
Now lets make some points about it.
In assigning a method to a class, the basic idea is that, that method or behaviour really belongs to that class - it is really a property of that class or type. For example, breathing for Animal. When this is the case, the behaviour is tied to class state (or data, or attributes, or variables). If a method does not access the class variables in any ways, then, that method may not belong there. At least it is the general rule.
Now, in your case, you have m1(), m2(), ... methods that appear in two different classes. This raises the possibility that they may not be really tied to the state of those classes. If so, then the better solution is to completely remove them into a new class.
If you do so,
You will also get rid of two classes, A and C, which now exist only for this purpose.
You get rid of two inheritance relationships. This makes you code much simpler.
And, you will achieve your objective of not repeating your self.
--
//Parent classes (child classes are now gone)
public class B {}
public class D {}
--
// Your new class
public class X {
// methods that previously were in A and C
m1();
m2();
...
}
Although, I have mixed feelings about its use; you can use the include directive.
Create a file, like this, named sharedMethods.as (or whatever you want). This is not a real class; it just includes code snippets:
public var mySharedMethod(mySharedMethodArguments:ArgumentType):void{
// do something
}
Then you can include it in your your other classes:
public class A extends B {
include "sharedMethods.as";
}
public class C extends D {
include "sharedMethods.as";
}
The code from your include file will be compiled as part of Class A and Class C.
You could also put your shared code in another class and have an instance of that class in both A and C. Then you either have to write wrapper methods or drill down the calls sort of like this:aInstance.sharedCodeObject.sharedMethod();
My intuition is that if you run into this a lot; you may have a problem with the object model that needs some refactoring.

How do Interfaces promote code reusablity?

A simple interview question.
How do interfaces help with code reusablity?
interfaces allows you to separate the implementation from the information the calling class cares about. This enables you to de-couple your classes from having intimate knowledge of classes it depends on.
Given the following interface:
public interface IRepository<T> {
void Save(T entity);
void Update(T entity);
void Delete(T entity);
}
A dependent class can be programmed against said interface and be "shielded" from the details.
public class SomeService {
private IRepository<Contact> _contactRepo;
public SomeService(IRepository<Contact> contactRepo){
_contactRepo = contactRepo;
}
}
Utilizing this pattern enables you to create different implementations of said interface:
public class LinqToSqlRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class EntityFrameworkRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class NHibernateRepository<Contact> : IRepository<Contact>
{ /* ... */ }
An interface decouples the consumer from the implementation details of a class. This helps enables reusability because the class implementing an interface can change, without needing to change the code consuming the implementation.
That's very confusing, maybe an example helps
public interface IUserAuthentication
{
public bool Authenticate(string name, string password);
}
Now I will write the consumer, it doesn't care how authentication is performed, it simply knows that it can authenticate users.
public class Consumer
{
private IUserAutentication _auth;
public Consumer(IUserAuthentication auth)
{
_auth = auth;
}
public void Working(string username, string password)
{
if (!_auth.Authenticate(username, password))
{
throw new Exception("error!");
}
}
}
The code above will work regardless of the implementation of the IUserAuthentication service. This is one way to reuse code.
Now I can implement the IUserAuthentication interface
public class AuthenticateJasons : IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return username == "Jason";
}
}
public class AuthenticateNoone: IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return false;
}
}
The point is that these implementations are irrelevant as far as the consumer is concerned. Also, this question is not related to ASP.NET the web framework. This is really a language/platform/framework agnostic question. The answer is the same regardless of the language you choose to implement with.
It is the Open and Close Principle, one of the important law of S.O.L.I.D Principles.
its idea is easy to change with minimum changes in the existing code. And ultimately helps with unit testing.
http://www.oodesign.com/design-principles.html

Design a class to be Unit testable

I am going though the Apress ASP.NET MVC 3 book and trying to ensure I create Unit Tests for everything possible but after spending a good part of a day trying to work out why edit's wouldn't save (see this SO question) I wanted to create a unit test for this.
I have worked out that I need to create a unit test for the following class:
public class EFProductRepository : IProductRepository {
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products {
get { return context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
context.Products.Add(product);
}
context.SaveChanges();
}
public void DeleteProduct(Product product) {
context.Products.Remove(product);
context.SaveChanges();
}
}
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
I am using Ninject.MVC3 and Moq and have created several unit tests before (while working though the previously mentioned book) so am slowly getting my head around it. I have already (hopefully correctly) created a constructor method to enable me to pass in _context:
public class EFProductRepository : IProductRepository {
private EFDbContext _context;
// constructor
public EFProductRepository(EFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
_context.SaveChanges();
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
_context.SaveChanges();
}
}
BUT this is where I start to have trouble... I believe I need to create an Interface for EFDbContext (see below) so I can replace it with a mock repo for the tests BUT it is built on the class DbContext:
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
from System.Data.Entity and I can't for the life of me work out how to create an interface for it... If I create the following interface I get errors due to lack of the method .SaveChanges() which is from the DbContext class and I can't build the interface using "DbContext" like the `EFDbContext is as it's a class not an interface...
using System;
using System.Data.Entity;
using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Concrete {
interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
}
The original Source can be got from the "Source Code/Downloads" on this page encase I have missed something in the above code fragments (or just ask and I will add it).
I have hit the limit of what I understand and no mater what I search for or read I can't seem to work out how I get past this. Please help!
The problem here is that you have not abstracted enough. The point of abstractions/interfaces is to define a contract that exposes behavior in a technology-agnostic way.
In other words, it is a good first step that you created an interface for the EFDbContext, but that interface is still tied to the concrete implementation - DbSet (DbSet).
The quick fix for this is to expose this property as IDbSet instead of DbSet. Ideally you expose something even more abstract like IQueryable (though this doesn't give you the Add() methods, etc.). The more abstract, the easier it is to mock.
Then, you're left with fulfilling the rest of the "contract" that you rely on - namely the SaveChanges() method.
Your updated code would look like this:
public class EFProductRepository : IProductRepository {
private IEFDbContext context;
public EFProductRepository(IEFDbContext context) {
this.context = context;
}
...
}
public interface IEFDbContext {
IDbSet<Product> Products { get; set; }
void SaveChanges();
}
BUT... the main question you have to ask is: what are you trying to test (conversely, what are you trying to mock out/avoid testing)? In other words: are you trying to validate how your application works when something is saved, or are you testing the actual saving.
If you're just testing how your application works and don't care about actually saving to the database, I'd consider mocking at a higher level - the IProductRepository. Then you're not hitting the database at all.
If you want to make sure that your objects actually get persisted to the database, then you should be hitting the DbContext and don't want to mock that part after all.
Personally, I consider both of those scenarios to be different - and equally important - and I write separate tests for each of them: one to test that my application does what it's supposed to do, and another to test that the database interaction works.
I guess your current code looks something like this (I put in the interface):
public class EFProductRepository : IProductRepository {
private IEFDbContext _context;
// constructor
public EFProductRepository(IEFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
**_context.SaveChanges();**
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
**_context.SaveChanges();**
}
}
public class EFDbContext : DbContext, IEFDbContext {
public DbSet<Product> Products { get; set; }
}
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
The problem is EFProductRepository now expects an object implementing the IEFDbContext interface, but this interface does not define the SaveChanges method used at the lines I put between the asteriskes so the compiler starts complaining.
Defining the SaveChanges method on the IEFDbContext interface solves your problem:
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
void SaveChanges();
}

Simplest approach for applying the MVP pattern on a Desktop (WinForms) and Web (ASP.NET) solution

Having almost no architectural experience I'm trying to design a DRY KISS solution for the .NET 4 platform taking an MVP approach that will eventually be implemented as a Desktop (WinForms) and Web (ASP.NET or Silverlight) product. I did some MVC, MVVM work in the past but for some reason I'm having difficulties trying to wrap my head around this particular one so in an effort to get a grip of the pattern I've decided to start with the simplest sample and to ask you guys for some help.
So assuming a quite simple Model as follows (in practice it'd most definitely be a WCF call):
internal class Person
{
internal string FirstName { get; set; }
internal string LastName { get; set; }
internal DateTime Born { get; set; }
}
public class People
{
private readonly List<Person> _people = new List<Person>();
public List<Person> People { get { return _people; } }
}
I was wondering:
What would be the most generic way to implement its corresponding View/Presenter triad (and helpers) for say, a Console and a Forms UI?
Which of them should be declared as interfaces and which as abstract classes?
Are commands always the recommended way of communication between layers?
And finally: by any chance is there a well-docummented, testeable, light framework to achieve just that?
I've written a number of apps that require a GUI and a winforms UI, the approach I have typically taken to implementing MVP is to create a generic view interface (you can subclass this for more specific views) and a controllerbase class which is given a view. You can then create different view implementations which inherit from the IView (or more specific view) interface
interface IView
{
event EventHandler Shown;
event EventHandler Closed;
void ShowView(IView parentView);
void CloseView();
}
class ControllerBase<T> where T: IView
{
private T _view;
public ControllerBase(T view)
{
_view = view;
}
public T View
{
get { return _view; }
}
public void ShowView(IView owner)
{
_view.ShowView(owner);
}
public void ShowView()
{
ShowView(null);
}
public void CloseView()
{
_view.CloseView();
}
}
Heres an example of how it would work in a specific case
interface IPersonView: IView
{
event EventHandler OnChangeName;
string Name { get; set; }
}
class PersonController: ControllerBase<IPersonView>
{
public PersonController(string name,IPersonView view) : base(view)
{
View.Name = name;
View.OnChangeName += HandlerFunction;
}
private void HandlerFunction(object sender, EventArgs e)
{
//logic to deal with changing name here
}
}
To implement this view in winforms, just make sure your form inherits from IPersonView and implements all the required properties/events and you're good to go. To instantiate the view/controller you'd do something like the following
PersonForm form = new PersonForm();
PersonController controller = new PersonController("jim",form);
controller.ShowView();

Resources