473,774 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strategy Pattern problem (or casting problem)

Hi,

I have a problem to implemente the strategy pattern. the problem come
from that a method take different arguments type (object in interface
and String / Int in implemented class).

When price3 instance call getPrice, the method invoked is the one of
PriceRule abstract class. But, I want to invoke the method of
PriceruleForReg ion. So I think the solution is somewhere on casting to
original type (PriceRuleForRe gion) but I don't how I can do that ?

Thank you for your help.
Example of code is here :

using System;

namespace ProblemCast_phi l
{

class Class1
{

[STAThread]
static void Main(string[] args)
{
// THIS IS WORKING FINE
PriceRuleForReg ion price1 = new PriceRuleForReg ion ("QC", 100);
PriceRuleForQua ntity price2 = new PriceRuleForQua ntity (1, 200);

Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price1.g etPrice ("QC"));
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price1.g etPrice ("ON"));

Console.WriteLi ne ("GetPrice based on quantity ordered (1) :
{0:c}",price2.g etPrice (1));
Console.WriteLi ne ("GetPrice based on quantity ordered (2) :
{0:c}",price2.g etPrice (2));

// THIS BLOCK FAILED.
PriceRule price3 = new PriceRuleForReg ion ("QC", 100);
PriceRule price4 = new PriceRuleForQua ntity (1, 200);
// EXCEPTION : The following line generate exception - See line 58
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price3.g etPrice ("QC"));
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price3.g etPrice ("ON"));

Console.WriteLi ne ("GetPrice based on quantity ordered (1) :
{0:c}",price4.g etPrice (1));
Console.WriteLi ne ("GetPrice based on quantity ordered (2) :
{0:c}",price4.g etPrice (2));


Console.ReadLin e ();

}
}
// ABSTRACT RULE CLASS
abstract class PriceRule
{
protected float m_price;
public PriceRule (float price)
{
this.m_price = price;
}

public float getPrice (object obj)
{
throw new ApplicationExce ption ("The program is not supose to call
this method.");
}

}

// FIRST IMPLEMENTATION FOR RULE
class PriceRuleForReg ion : PriceRule
{
private string m_region;

public PriceRuleForReg ion (string region, float price)
:base (price)
{
this.m_region = region;
}

public float getPrice (string region)
{
if (this.m_region == region) return m_price;

return -1;
}

}

// FIRST IMPLEMENTATION FOR RULE
class PriceRuleForQua ntity : PriceRule
{
private int m_quantity;

public PriceRuleForQua ntity (int quantity, float price)
:base (price)
{
this.m_quantity = quantity;
}

public float getPrice (int quantity)
{
if (this.m_quantit y == quantity) return this.m_price;

return -1;
}

}

}
Philippe SILLON
Nov 16 '05 #1
2 1797
philippe sillon wrote:
I have a problem to implemente the strategy pattern. the problem come
from that a method take different arguments type (object in interface
and String / Int in implemented class).

When price3 instance call getPrice, the method invoked is the one of
PriceRule abstract class. But, I want to invoke the method of
PriceruleForReg ion. So I think the solution is somewhere on casting to
original type (PriceRuleForRe gion) but I don't how I can do that ?
You should make GetPrice virtual in teh base class and override the method
in the derived classes.

The strategy pattern works like this:

public class Foo
{
// .. init code, constructors etc.

public virtual void Strategic()
{
}

public void MyCoolMethod()
{
// some code

Strategic();

// other code
}
}

public class Bar:Foo
{
public override void Strategic()
{
// strategic method implementation
}
}
now when you do this:
Bar b = new Bar();
b.MyCoolMethod( );

b's implementation will be called, but..

Foo f = new Bar();
f.MyCoolMethod( );

also will call b's implementation.

However your code doesn't show a schema like this where you 'inject' code via
polymorphism into a base class' implementation, as you don't override a base
class method which is called by the base class logic.

Frans.


Thank you for your help.
Example of code is here :

using System;

namespace ProblemCast_phi l
{

class Class1
{

[STAThread]
static void Main(string[] args)
{
// THIS IS WORKING FINE
PriceRuleForReg ion price1 = new PriceRuleForReg ion ("QC", 100);
PriceRuleForQua ntity price2 = new PriceRuleForQua ntity (1, 200);

Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price1.g etPrice ("QC"));
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price1.g etPrice ("ON"));

Console.WriteLi ne ("GetPrice based on quantity ordered (1) :
{0:c}",price2.g etPrice (1));
Console.WriteLi ne ("GetPrice based on quantity ordered (2) :
{0:c}",price2.g etPrice (2));

// THIS BLOCK FAILED.
PriceRule price3 = new PriceRuleForReg ion ("QC", 100);
PriceRule price4 = new PriceRuleForQua ntity (1, 200);
// EXCEPTION : The following line generate exception - See line 58
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price3.g etPrice ("QC"));
Console.WriteLi ne ("GetPrice based on Quebec :
{0:c}",price3.g etPrice ("ON"));

Console.WriteLi ne ("GetPrice based on quantity ordered (1) :
{0:c}",price4.g etPrice (1));
Console.WriteLi ne ("GetPrice based on quantity ordered (2) :
{0:c}",price4.g etPrice (2));


Console.ReadLin e ();

}
}
// ABSTRACT RULE CLASS
abstract class PriceRule
{
protected float m_price;
public PriceRule (float price)
{
this.m_price = price;
}

public float getPrice (object obj)
{
throw new ApplicationExce ption ("The program is not supose to call
this method.");
}

}

// FIRST IMPLEMENTATION FOR RULE
class PriceRuleForReg ion : PriceRule
{
private string m_region;

public PriceRuleForReg ion (string region, float price)
:base (price)
{
this.m_region = region;
}

public float getPrice (string region)
{
if (this.m_region == region) return m_price;

return -1;
}

}

// FIRST IMPLEMENTATION FOR RULE
class PriceRuleForQua ntity : PriceRule
{
private int m_quantity;

public PriceRuleForQua ntity (int quantity, float price)
:base (price)
{
this.m_quantity = quantity;
}

public float getPrice (int quantity)
{
if (this.m_quantit y == quantity) return this.m_price;

return -1;
}

}

}
Philippe SILLON


--
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP
Nov 16 '05 #2
Hi,

Ok, but what append if I want to add new function but with different
signature (like add one parameter string).
I don't want to cast foo variable (type Foo) to type Bar because I can
have different implementation of Foo class.
It's like I need to cast but the cast depend on instance type (foo
variable is a Bar type but the reference is a Foo type)

Thank you for your help.
He is an example :

using System;

namespace ProblemCast_phi l
{
public class Class2
{
static void Main (string[] args)
{

// EVERYTHING IS PERFECT EXCEPT THE LAST LINE
Bar bar = new Bar ();
bar.Strategic ();

Foo foo = new Bar ();
foo.Strategic ();
foo.MyCoolMetho d ();

// THIS LINE. I GOT THE FOLLWING ERROR AT COMPILATION :
// Class2.cs(22): No overload for method 'Strategic' takes '1'
arguments
foo.Strategic ("From Philippe");

Console.ReadLin e ();
}
}

public class Foo
{
// .. init code, constructors etc.

public virtual void Strategic()
{
Console.WriteLi ne ("Call Foo.Strategic") ;
}

public void MyCoolMethod()
{
// some code
Console.WriteLi ne ("Call Foo.MyCollMetho d");

Strategic();

// other code
}
}

public class Bar:Foo
{
public override void Strategic()
{
// strategic method implementation
Console.WriteLi ne ("Call Bar.Strategic") ;
}

public void Strategic (string message)
{
// strategic method implementation
Console.WriteLi ne ( "Call Bar.Strategic with message" + message );
}

}
}
Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2495
by: ghostdog | last post by:
hi, i got this opengl/c++ code: <code> void render(CMesh *mesh){ ... float *pVertices; int *pIndices;
3
3256
by: syncman | last post by:
I think there are 2 options for how to implement the Strategy pattern. One is to use polymorphism; derived classes have the same interface and can be plugged in. The other is to use templates: Instantiate the class, passing in a functor (algorithm). Code samples below. The problem with the first way is that the interface must be the same (parameters passed in) for all strategies. The problem with the second way is that there is no...
1
1687
by: fabrice | last post by:
Hello I have a little problem with casting in a Datagrid Control. I'm using Option Strict in my web application. In a Template Column, I put in an ImageButton Control with a Command Argument using Container.DataItem. Différent expressions as System.Convert.ToString(Container.DataItem("Column"))) bring an Error :
5
2069
by: pythoncurious | last post by:
Hi python experts In C++ I can do something like this: class Base { public: void f() { this->f_(); } private: virtual void f_() = 0; };
0
1360
by: ltruett | last post by:
I'm almost done my series of design patterns using PHP 5. Today's pattern is the Strategy Pattern. http://www.fluffycat.com/PHP-Design-Patterns/Strategy/ In the Stratedy Pattern a "family of algorythms" is used interchangably by calling clients. This is the second pattern in as many days as I've used my older work with patterns in Java, and again I liked the old example when I first
1
2491
by: Nick | last post by:
Hi, I read somewhere recently that the strategy pattern could be used instead of using switch command on an enum (for example). How would this work? A small example would be great. Thanks, Nick
8
2154
by: CK | last post by:
Good Morning All, I am writing an app to calculate the cost of a hotel room. I am new to c++. I have decided to try using the Strategy Design Pattern. I want a superclass HotelRoom, and then make 3 classes that inherit from it. SuiteRoom, StandardRoom, and DeluxeRoom. The price of the room is based on 3 factors, if there is are more then 2 people in the room, there is a $10 charge per persons over 2, if they add an extra bed, and the room...
12
2136
by: Phil Endecott | last post by:
Dear Experts, I need a function that takes a float, swaps its endianness (htonl) in place, and returns a char* pointer to its first byte. This is one of a family of functions that prepare different data types for passing to another process. I have got confused by the rules about what won't work, what will work, and what might work, when casting. Specifically, I have an implementation that works until I remove my debugging, at which...
1
1176
by: guncrew | last post by:
Hello I am starting to use Python. I found a nice little example for subsituting and splitting texts and counting words separated by defined expressions (in the example , and blanks). Unfotunately there is an error in this example regarding the casting of strings: (see the code below): #zerleg.py import re try: fh=open('input.txt','r') summe=0 n=0
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10040
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.