I have 2 cases wheter a method can be considered a Factory Design Pattern, this example is in C#, altought, can apply to other programming languages:
enum NinjaTypes {
Generic,
Katanna,
StarThrower,
Invisible,
Flyer
}
public class Ninja {
public string Name { get; set; }
public void jump() { ... }
public void kickAss() { ... }
}
public class KatannaNinja: Ninja {
public void useKatanna() { ... }
}
public class StarNinja: Ninja {
public void throwStar() { ... }
}
public class InvisibleNinja: Ninja {
public void becomeInvisible() {...}
public void becomeVisible() {...}
}
public class FlyNinja: Ninja {
public void fly() {...}
public void land() {...}
}
public class NinjaSchool {
// always return generic type
public Ninja StandardStudent() {...}
// may return other types
public Ninja SpecialityStudent(NinjaTypes WhichType) {...}
}
The method StandardStudent() always return a new object of the same type, the SpecialityStudent(...), may return new objects from different classes that share the same superclass / base type. Both methods are intentionally not virtual.
The question is, are both methods "Factory Design Pattern" ?
My guess is that SpecialityStudent(...) is, but StandardStudent() is not. If the second is not, can be considered another design pattern ?
I don't think that nor a FactoryMethod`nor AbstractFactory patterns forbid the user to use a parameter to specify a type to the creator method. Anyway you should consider at least 2 things in your design:
Factory methods are useful to keep the client unaware of the concrete type of the created object. From my point of view isn't wrong to specify explicitly the type of object to be created, but pay attention to not put too much knowledge on the client classes to be able to construct objects through the factory.
Both your factory methods return a Ninja object, but some of your ninjas extended class declare additional methods, which client is unaware of. If your client need to use those methods explicitly then maybe you have to make some consideration on your design.
I think this actually looks like an Anti-Pattern. There's really nothing to stop a consumer of this code to just instantiate the specialty ninjas directly. What benefit is there to using the Ninja School? I think the whole point of the Factory pattern is to encapsulate the process of instantiating an object so that you can hide the details from the consumer. Any time you make a change to the "creation" logic, it doesn't break anyone's code.
And it just looks like a bad idea to have all the types in an enum. I don't have a concrete reason to back up this claim other than, "it feels wrong".
After reviewing the Abstract Factory pattern, I can see how you could go about turning this into an Abstract Factory, but I don't see the benefit given the semantics of your objects. I think that if you want to have a Ninja factory, you'd have to make the individual constructors protected or internal, so they can't be called directly by consumer code
Both your methods can be seen as factories. But the second one is a little awkward to use:
var school = new NinjaSchool();
var ninja = school.SpecialtyStudent(NinjaTypes.Flyer);
// to fly you must cast
((FlyingNinja)ninja).Fly();
You've already asked for a flyer, so you shouldn't need to cast. A better option might be to eliminate the enum and ask for the exact ninja that you want:
var flyingNinja = school.FlyingStudent(); // you get a FlyingNinja
flyingNinja.Fly();
Another thing to consider in your design is this: what if you want an invisible ninja that can fly? Or a katana ninja that also throws stars? That will shake up your hierarchy and challenge your belief in inheritance.
It's almost a factory method. I would do something like:
enum NinjaTypes {
Generic, Katanna, StarThrower, Invisible, Flyer
}
class Ninja {
String Name;
void jump() {
}
void kickAss() {
}
void useKatanna() {
System.out.println("nothing happens");
}
void throwStar() {
System.out.println("nothing happens");
}
void becomeInvisible() {
System.out.println("nothing happens");
}
void becomeVisible() {
System.out.println("nothing happens");
}
void fly() {
System.out.println("nothing happens");
}
void land() {
System.out.println("nothing happens");
}
}
class StarThrowerNinja extends Ninja {
void throwStar() {
System.out.println("throwing star");
}
}
class NinjaSchool {
static Ninja create(NinjaTypes WhichType) {
switch (WhichType) {
case Generic:
return new Ninja();
case StarThrower:
return new StarThrowerNinja();
default:
return null;
}
}
}
public class Main {
public static void main(String[] args) {
Ninja generic=NinjaSchool.create(NinjaTypes.Generic);
generic.throwStar();
Ninja starThrower=NinjaSchool.create(NinjaTypes.StarThrower);
starThrower.throwStar();
}
}
Related
I was wondering how I should decide to create an object, on method or class instance.Below a few examples to clarify. I want to the best approach to know how I should determine to choose between example 1 and 2.
IMPORTANT: Consider this a Windows Service (SVC) hosted in IIS.
Example 1
public class mySvcService
{
ReusableClass rClass = new ReusableClass();
public void MethodOne()
{
//Do Method One Stuff...
rClass.doSomething();
}
public void MethodTwo()
{
//Do Method Two Stuff...
rClass.doSomething();
}
}
public class ReusableClass
{
string valueOne;
string valueTwo;
string valueThree;
public void doSomething()
{
//DoSomeWork
}
}
Example 2
public class mySvcService
{
public void MethodOne()
{
ReusableClass rClass = new ReusableClass();
//Do Method One Stuff...
rClass.doSomething();
}
public void MethodTwo()
{
ReusableClass rClass = new ReusableClass();
//Do Method Two Stuff...
rClass.doSomething();
}
}
public class ReusableClass
{
string valueOne;
string valueTwo;
string valueThree;
public void doSomething()
{
//DoSomeWork
}
}
It is all about state. Will the object preserve some state between the two method calls, or even within the method, or not? If so, you should keep the object alive. Else, you can create a new object every time you call the method, or maybe even make the method static if there is never any state involved.
So:
Class preserves state that should be kept across methods: make a class variable or pass the object along the methods.
Class preserves state that should be kept within the same method: make a local variable.
Class doesn't preserve any state: make the method static, no instance needed.
The golden rule is to keep the scope as local as possible. From the second example if you are going to use doSomething() everywhere then it is better to create it once and have class level scope. If you need doSomething() only in one method, create the object locally within the method.
It is better to leave it inside of a method. Usually, it is being done inside of the constructor. This has the favor that it can incorporate a factory for different scenarios, or that it can be easily injected. I would strongly suggest to separate the responsibilities of the properties and let them be used as needed.
If you want to limit the scope of the object to a method, It can be done by using "Method injection" as shown below. You can use the other setter and constructor injection methods if the scope of the object is through out the class.
public interface IReusable
{
void doSomething();
}
public class Reusable: IReusable
{
public void doSomething()
{
//To Do: Some Stuff
}
}
public class mySvcService
{
private IReusable _reuse;
public void MethodOne(IReusable reuse)
{
this._reuse= reuse;
_reuse.doSomething();
}
public void MethodTwo(IReusable reuse)
{
this._reuse= reuse;
_reuse.doSomething();
}
}
The following code is a valid C# construct that compile juste fine.
public class Weird : Weird.IWeird
{
private interface IWeird
{
}
}
What would be the possible uses of this?
Edit: This question is more specific that this one: "What is a private interface?". It shows that it's possible to implement a private interface from the parent type itself, which seems to be rather pointless. The only use I can think of would be a weird case of interface segregation where you would want to pass an instance of the parent class to a nested class instance as IWeird.
This is probably one of these situations in compiler development when prohibiting something has a higher cost than allowing it. Prohibiting this use would require writing and maintaining code to detect this situation, and report an error; if the feature works as-is, this is an additional work for the team, and it could be avoided. After all, perhaps someone with good imagination could figure out a way to use the feature.
As far as a useful example goes, one potential use is to make another implementation in the class, and use it as an alternative without exposing it to the users of the API:
public class Demo : Demo.Impl {
// Private interface
private interface Impl {
public bool IsValidState {get;}
void DoIt();
}
// Implementation for the error state
private class Error : Impl {
public bool IsValidState { get { return false; } }
public void DoIt() {
Console.WriteLine("Invalid state.");
}
}
private readonly string name;
// Implementation for the non-error state
public bool IsValidState { get { return true; } }
public void DoIt() {
Console.WriteLine("Hello, {0}", name);
}
// Constructor assigns impl depending on the parameter passed to it
private readonly Impl impl;
// Users are expected to use this method and property:
public bool IsValid {
get {
return impl.IsValidState;
}
}
public void SayHello() {
impl.DoIt();
}
// Constructor decides which impl to use
public Demo(string s) {
if (s == null) {
impl = new Error();
} else {
impl = this;
name = s;
}
}
}
As far as best practices go, this design is questionable at best. In particular, I would create a second nested class for the non-error implementation, rather than reusing the main class for that purpose. However, there is nothing terribly wrong with this design (apart from the fact that both IsValidState and DoIt are visible) so it was OK of the C# team to allow this use.
I've been having trouble even defining what I am looking for.
I am writing an app to determine winners in a tournament. I would like my base class to be able to change it's inheritance based on how many people are playing, given that multiple inheritance is not an option, and probably wouldn't be a very good one the more i think on it.
I see something along the lines of
class Base
{
//Constructor receiving the quantity of players
public Base (int quantityOfPlayers)
{
//Changes Base inheritance dynamically based on QuantityOfPlayers
switch (quantityOfPlayers)
{
case 4: (Base : FourPlayers);
case 5: (Base : FivePlayers);
}
}
}
But of course i can't seem to find a means (if there is one) of dynamically changing the inheritance like that. Otherwise I'm stuck using more complicated means though each of the getter and setter functions are going to be essentially the same.
Very good solutions. let me add that I'm using a GUI not the console.
I have to think on this, the factory class is good, but it has convinced me I'm over thinking my approach.
There is a software design pattern called strategy pattern for this kind of situation.
Define an interface for the game strategy
public interface IGameStrategy
{
// Things that depend on the number of players, go here...
}
The right strategy gets injected into the game through constructor injection
public class Game
{
private IGameStrategy _strategy;
// Constructor injection
public Game(IGameStrategy strategy)
{
_strategy = strategy;
}
// Things common to all types of games go here...
}
Define a factory method like this:
private IGameStrategy CreateGameStrategy(int numberOfPlayers)
switch (numberOfPlayers)
{
case 4:
return FourPlayersStrategy();
case 5:
return FivePlayersStrategy();
default:
throw new ArgumentException("Invalid number of players");
}
}
Then create a game like this:
var game = new Game(CreateGameStrategy(numberOfPlayers));
Of course the strategy classes implement the interface. They can do so directly or they can inherit a common abstract base class implementing the interface.
The game logic is split into things common to all types of games implemented in the Game class and things specific to the number of players implemented in the strategy classes.
You could create a factory class that generates the proper class based on the number of players:
public class PlayerQtyFactory
{
//You can add any other args you might need as well
public BaseClass CreatePlayerQty(int numPlayers)
{
switch (numPlayers)
{
Case 2:
return new TwoPlayers();
Case 3:
return new ThreePlayers();
{
}
}
Without knowing more about what you are trying to do, it is hard to say if this is the best approach, but it is certainly A aproach.
For this particular situation I would use a factoryesque (or just plan factory) solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tester
{
//declare common functionality
public interface ISharedFunctionality
{
//put all shared functionality here
void SomeMethod();
void SomeOtherMethod();
void DifferentMethod();
string Name {get;set;}
}
public interface ISinglePlayerFunctionality : ISharedFunctionality
{
//put single player functionality here
void SomeOtherMethod();
void SomeMethod();
}
public interface IMultiplePlayerFunctionality : ISharedFunctionality
{
//put multiplayer functionality here
void DifferentMethod();
void SomeMethod();
}
public class ImplementationBase : ISharedFunctionality
{
//shared implementation here
public void SomeMethod()
{
//do stuff
Console.WriteLine("In Base");
}
public void SomeOtherMethod()
{
//one you don't want to inherit in multiplayer
Console.WriteLine("In Base");
}
public void DifferentMethod()
{
Console.WriteLine("In Base");
}
public string Name
{
get;
set;
}
}
public class MultiPlayerImplementation : ImplementationBase, IMultiplePlayerFunctionality
{
//multiplay impl
// you inherit some method but don't want to inherit
//SomeOtherMethod when cast to ISharedFunctionality
void ISharedFunctionality.SomeMethod()
{
//when cast to ISharedFunctionality this method will execute not inherited
Console.WriteLine("In MutilPlayImplementation");
}
}
public class SinglePlayerImplementation : ImplementationBase , ISinglePlayerFunctionality
{
//singleplay impl
void ISharedFunctionality.SomeOtherMethod()
{
Console.WriteLine("In SinglePlayerImplementation" );
}
}
public class Factory
{
//logic to decide impl here
public ISharedFunctionality Create(int numberOfPlayer)
{
if (numberOfPlayer == 1)
{
return new SinglePlayerImplementation();
}
else if(numberOfPlayer > 1)
{
return new MultiPlayerImplementation();
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
var factory = new Factory();
var results = new[]{factory.Create(1) , factory.Create(2) };
int j=0;
foreach (var i in results)
{
///for single player will be base
///multiplaryer will be mutliplayer
i.SomeMethod();
//for single player will be single player
// for multiplayer will be base
i.SomeOtherMethod();
i.DifferentMethod();
i.Name = "Item-Number-" + j;
Console.WriteLine();
}
}
}
}
The benefit to this is two fold, you now no longer have ambiguity in terms of what method is being called, and you have a unified place to construct future implementations based off of similair contracts (i.e. three player behavior, different menu behavior, and it might be even less code if you want the exact same methods to just behave differently
I am doing some research on design pattern implementation variants, i have come across and read some examples implemented here http://www.codeproject.com/Articles/37547/Exploring-Factory-Pattern and http://www.oodesign.com/factory-pattern.html. My focus of concern is when implementing factory pattern without reflection . the stated articles said that we need to register objects not classes which seems fine and logical to me but when seeing the implementation i see the duplication of objects e.g in the code below
// Factory pattern method to create the product
public IRoomType CreateProduct(RoomTypes Roomtype)
{
IRoomType room = null;
if (registeredProducts.Contains(Roomtype))
{
room = (IRoomType)registeredProducts[Roomtype];
room.createProduct();
}
if (room == null) { return room; }
else { return null; }
}
// implementation of concrete product
class NonACRoom : IRoomType
{
public static void RegisterProduct()
{
RoomFactory.Instance().RegisterProduct(new NonACRoom(), RoomTypes.NonAcRoom);
}
public void getDetails()
{
Console.WriteLine("I am an NON AC Room");
}
public IRoomType createProduct()
{
return new NonACRoom();
}
}
the method RegisterProduct is used for self registeration, we have to call it anyways before creating factory object i.e before some where in the main class of the client or anywhere applicable that ensure its calling. below is we are creating a new product and in the method above we are creating again a new product which seems non sense. any body comment on that
I have done something similar to this in the past. This is essentially what I came up with (and also doing away with the whole "Type" enumeration):
public interface ICreator
{
IPart Create();
}
public interface IPart
{
// Part interface methods
}
// a sample creator/part
public PositionPartCreator : ICreator
{
public IPart Create() { return new PositionPart(); }
}
public PositionPart : IPart
{
// implementation
}
Now we have the factory itself:
public sealed class PartFactory
{
private Dictionary<Type, IPartCreator> creators_ = new Dictionary<Type, IPartCreator>();
// registration (note, we use the type system!)
public void RegisterCreator<T>(IPartCreator creator) where T : IPart
{
creators_[typeof(T)] = creator;
}
public T CreatePart<T>() where T: IPart
{
if(creators_.ContainsKey(typeof(T))
return creators_[typeof(T)].Create();
return default(T);
}
}
This essentially does away with the need for a "type" enumeration, and makes things really easy to work with:
PartFactory factory = new PartFactory();
factory.RegisterCreator<PositionPart>(new PositionPartCreator());
// all your other registrations
// ... later
IPart p = factory.CreatePart<PositionPart>();
The first creation is used to give something to work on to RegisterProduct. Probably, the cost of that object is neglectable. It's done during initialization and won't matter much.
This instance is required though because in C# you need an object to call createProduct on. This is because you can't use reflection to store a reference to a type instead of a reference to an object.
What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.