Search Results

Search found 5544 results on 222 pages for 'pattern'.

Page 7/222 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Pattern matching in Perl ala Haskell

    - by Paul Nathan
    In Haskell (F#, Ocaml, and others), I can do this: sign x | x > 0 = 1 | x == 0 = 0 | x < 0 = -1 Which calculates the sign of a given integer. This can concisely express certain logic flows; I've encountered one of these flows in Perl. Right now what I am doing is sub frobnicator { my $frob = shift; return "foo" if $frob eq "Foomaticator"; return "bar" if $frob eq "Barmaticator"; croak("Unable to frob legit value: $frob received"); } Which feels inexpressive and ugly. This code has to run on Perl 5.8.8, but of course I am interested in more modern techniques as well.

    Read the article

  • Strategy Design Pattern -- *dynamic* !!!

    - by alexeypro
    My application will have different strategies for my objects. What's the best way of implementing that? I would really love the case when we can make strategy classes implementation dynamically loaded from, say, some relational database. Not sure how do that better, though. What's the best approach? Idea is that say we want to apply to object MyObj strategy Strategy123 then we just load from database by ID 123 the object, deserialize it, get the Strategy class, and use it with MyObj. The maintenance while sounds easier from the first look can be a pain in the long run if Strategy interfaces changes, etc. What can I do also? I want to find solution when I should be keeping Strategy classes in codebase -- just for the sake that I don't need code change and re-deployment of the application if my Strategy changes, or I add new strategy. Please advise!

    Read the article

  • Question regarding factory pattern

    - by eriks
    I have a factory class to build objects of base class B. The object (D) that uses this factory received a list of strings representing the actual types. What is the correct implementation: the factory receives an Enum (and uses switch inside the Create function) and D is responsible to convert the string to Enum. the factory receives a string and checks for a match to a set of valid strings (using ifs') other implementation i didn't think of.

    Read the article

  • Need a design pattern for representing multiple information sources

    - by hsmit
    I'm building a Java application that retrieves information from differing information sources. I'm using a sensor, a set of RecordStores and a few online web services. In the basic application all these resources are loaded by default. Some of these sources are directly read in a separate thread (load database, read sensor etc.). From this basic application some functions are started that use these sources. The classes that contain these functions (usually combining multiple sources information) are currently paramterized with a set of resources like this: AppPart a1 = new AppPart(source1, source2, source3); I could also do it like this AppPart a1 = new AppPart(this); ..where I need to make my sources public in order to read them. I'm also thinking about a kind of stage/collection to publish all sources on, e.g: public SourceCollectionStage sStage = new SourceCollectionStage(); and later: sStage.getSensor(); .. for example. What do you guys think is the best or most often used way to do this? Btw: the user interface is often implemented by the specific funtion classes, not by the main class. Should I do this in another way?

    Read the article

  • "Pattern matching" of algebraic type data constructors

    - by jetxee
    Let's consider a data type with many constructors: data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int I want to write a function to check if two values are produced with the same constructor: sameK (Alpha _) (Alpha _) = True sameK (Beta _) (Beta _) = True sameK (Gamma _ _) (Gamma _ _) = True sameK _ _ = False Maintaining sameK is not much fun, it is potentially buggy. For example, when new constructors are added to T, it's easy to forget to update sameK. I omitted one line to give an example: -- it’s easy to forget: -- sameK (Delta _) (Delta _) = True The question is how to avoid boilerplate in sameK? Or how to make sure it checks for all T constructors? The workaround I found is to use separate data types for each of the constructors, deriving Data.Typeable, and declaring a common type class, but I don't like this solution, because it is much less readable and otherwise just a simple algebraic type works for me: {-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable class Tlike t where value :: t -> t value = id data Alpha = Alpha Int deriving Typeable data Beta = Beta Int deriving Typeable data Gamma = Gamma Int Int deriving Typeable data Delta = Delta Int deriving Typeable instance Tlike Alpha instance Tlike Beta instance Tlike Gamma instance Tlike Delta sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool sameK a b = typeOf a == typeOf b

    Read the article

  • Is a "factory" method the right pattern?

    - by jdt141
    Hey all - So I'm working to improve an existing implementation. I have a number of polymorphic classes that are all composed into a higher level container class. The problem I'm dealing with at the moment is that the higher level container class, well, sucks. It looks something like this, which I really don't have a problem with (as the polymorphic classes in the container should be public). My real issue is the constructor... /* * class1 and class 2 derive from the same superclass */ class Container { public: boost::shared_ptr<ComposedClass1> class1; boost::shared_ptr<ComposedClass2> class2; private: ... } /* * Constructor - builds the objects that we need in this container. */ Container::Container(some params) { class1.reset(new ComposedClass1(...)); class2.reset(new ComposedClass2(...)); } What I really need is to make this container class more re-usable. By hard-coding up the member objects and instantiating them, it basically isn't and can only be used once. A factory is one way to build what I need (potentially by supplying a list of objects and their specific types to be created?) Other ways to get around this problem? Seems like someone should have solved it before... Thanks!

    Read the article

  • What design pattern will you choose ?

    - by MemoryLeak
    I want to design a class, which contains a procedure to achieve a goal. And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly. in such a case, what design patter will you use ? which can make sure that the user must call the public method according some ordering. If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?

    Read the article

  • Factory Method pattern and public constructor

    - by H4mm3rHead
    Hi, Im making a factory method that returns new instances of my objects. I would like to prevent anyone using my code from using a public constructor on my objects. Is there any way of doing this? How is this typically accomplished: public abstract class CarFactory { public abstract ICar CreateSUV(); } public class MercedesFactory : CarFactory { public override ICar CreateSUV() { return new Mercedes4WD(); } } I then would like to limit/prevent the other developers (including me in a few months) from making an instance of Mercedes4WD. But make them call my factory method. How to?

    Read the article

  • Software Architecture: Unit of Work design pattern discussion

    - by santiagobasulto
    Hey everybody. According Martin Fowler's Unit of Work description: "Maintains a list of objects that are affected by a business transaction and coordinates the writing out of changes and resolution of concurrency problems." Avoiding very small calls to the database, which ends up being very slow I'm wondering. If we just delimit it to database transaction management, won't prepare statements help with this?

    Read the article

  • NSString simple pattern matching

    - by SirRatty
    Hi all, Mac OS 10.6, Cocoa project, 10.4 compatibility required. (Please note: my knowledge of regex is quite slight) I need to parse NSStrings, for matching cases where the string contains an embedded tag, where the tag format is: [xxxx] Where xxxx are random characters. e.g. "The quick brown [foxy] fox likes sox". In the above case, I need to grab the string "foxy". (Or nil if no tag is found.) Each string will only have one tag, and the tag can appear anywhere within the string, or may not appear at all. Could someone please help with a way to do that, preferably without having to include another library such as RegexKit. Thank you for any help.

    Read the article

  • Regex and Pattern Matching in Scala

    - by Bruce Ferguson
    I am not strong in regex, and pretty new to Scala. I would like to be able to find a match between the first letter of a word, and one of the letters in a group such as "ABC". In pseudocode, this might look something like: case Process(word) => word.firstLetter match { case([a-c][A-C]) => case _ => } } but I don't know how to grab the first letter in Scala instead of Java, how to express the regular expression properly, nor if it's possible to do this within a case class. Any suggestions? Thanks in advance. Bruce

    Read the article

  • Building a control-flow graph from an AST with a visitor pattern using Java

    - by omegatai
    Hi guys, I'm trying to figure out how to implement my LEParserCfgVisitor class as to build a control-flow graph from an Abstract-Syntax-Tree already generated with JavaCC. I know there are tools that already exist, but I'm trying to do it in preparation for my Compilers final. I know I need to have a data structure that keeps the graph in memory, and I want to be able to keep attributes like IN, OUT, GEN, KILL in each node as to be able to do a control-flow analysis later on. My main problem is that I haven't figured out how to connect the different blocks together, as to have the right edge between each blocks depending on their nature: branch, loops, etc. In other words, I haven't found an explicit algorithm that could help me build my visitor. Here is my empty Visitor. You can see it works on basic langage expressions, like if, while and basic operations (+,-,x,^,...) public class LEParserCfgVisitor implements LEParserVisitor { public Object visit(SimpleNode node, Object data) { return data; } public Object visit(ASTProgram node, Object data) { data = node.childrenAccept(this, data); return data; } public Object visit(ASTBlock node, Object data) { } public Object visit(ASTStmt node, Object data) { } public Object visit(ASTAssignStmt node, Object data) { } public Object visit(ASTIOStmt node, Object data) { } public Object visit(ASTIfStmt node, Object data) { } public Object visit(ASTWhileStmt node, Object data) { } public Object visit(ASTExpr node, Object data) { } public Object visit(ASTAddExpr node, Object data) { } public Object visit(ASTFactExpr node, Object data) { } public Object visit(ASTMultExpr node, Object data) { } public Object visit(ASTPowerExpr node, Object data) { } public Object visit(ASTUnaryExpr node, Object data) { } public Object visit(ASTBasicExpr node, Object data) { } public Object visit(ASTFctExpr node, Object data) { } public Object visit(ASTRealValue node, Object data) { } public Object visit(ASTIntValue node, Object data) { } public Object visit(ASTIdentifier node, Object data) { } } Can anyone give me a hand? Thanks!

    Read the article

  • Apply PHP regex replace on a multi-line repeted pattern

    - by Hussain
    Let's say I have this input: I can haz a listz0rs! # 42 # 126 I can haz another list plox? # Hello, world! # Welcome! I want to split it so that each set of hash-started lines becomes a list: I can haz a listz0rs! <ul> <li>42</li> <li>126</li> </ul> I can haz another list plox? <ul> <li>Hello, world!</li> <li>Welcome!</li> </ul> If I run the input against the regex "/(?:(?:(?<=^# )(.*)$)+)/m", I get the following result: Array ( [0] => Array ( [0] => 42 ) Array ( [0] => 126 ) Array ( [0] => Hello, world! ) Array ( [0] => Welcome! ) ) This is fine and dandy, but it doesn't distinguish between the two different lists. I need a way to either make the quantifier return a concatenated string of all the occurrences, or, ideally, an array of all the occurrences. Idealy, this should be my output: Array ( [0] = Array ( [0] = 42 [1] = 126 ) Array ( [0] = Hello, world! [1] = Welcome! ) ) Is there any way of achieving this, and if not, is there a close alternative? Thanks in advance!

    Read the article

  • F# pattern matching when mixing DU's and other values

    - by Roger Alsing
    What would be the most effective way to express the following code? match cond.EvalBool() with | true -> match body.Eval() with | :? ControlFlowModifier as e -> match e with | Break(scope) -> e :> obj //Break is a DU element of ControlFlowModifier | _ -> next() //other members of CFM should call next() | _ -> next() //all other values should call next() | false -> null cond.EvalBool returns a boolean result where false should return null and true should either run the entire block again (its wrapped in a func called next) or if the special value of break is found, then the loop should exit and return the break value. Is there any way to compress that block of code to something smaller?

    Read the article

  • Apply PHP regex replace on a multi-line repeated pattern

    - by Hussain
    Let's say I have this input: I can haz a listz0rs! # 42 # 126 I can haz another list plox? # Hello, world! # Welcome! I want to split it so that each set of hash-started lines becomes a list: I can haz a listz0rs! <ul> <li>42</li> <li>126</li> </ul> I can haz another list plox? <ul> <li>Hello, world!</li> <li>Welcome!</li> </ul> If I run the input against the regex "/(?:(?:(?<=^# )(.*)$)+)/m", I get the following result: Array ( [0] => Array ( [0] => 42 ) [1] => Array ( [0] => 126 ) [2] => Array ( [0] => Hello, world! ) [3] => Array ( [0] => Welcome! ) ) This is fine and dandy, but it doesn't distinguish between the two different lists. I need a way to either make the quantifier return a concatenated string of all the occurrences, or, ideally, an array of all the occurrences. Ideally, this should be my output: Array ( [0] => Array ( [0] => 42 [1] => 126 ) [1] => Array ( [0] => Hello, world! [1] => Welcome! ) ) Is there any way of achieving this, and if not, is there a close alternative? Thanks in advance!

    Read the article

  • Problem updating through LINQtoSQL in MVC application using StructureMap, Repository Pattern and UoW

    - by matt
    I have an ASP MVC application using LINQ to SQL for data access. I am trying to use the Repository and Unit of Work patterns, with a service layer consuming the repositories and unit of work. I am experiencing a problem when attempting to perform updates on a particular repository. My application architecture is as follows: My service class: public class MyService { private IRepositoryA _RepositoryA; private IRepositoryB _RepositoryB; private IUnitOfWork _unitOfWork; public MyService(IRepositoryA ARepositoryA, IRepositoryB ARepositoryB, IUnitOfWork AUnitOfWork) { _unitOfWork = AUnitOfWork; _RepositoryA = ARepositoryA; _RepositoryB = ARepositoryB; } public PerformActionOnObject(Guid AID) { MyObject obj = _RepositoryA.GetRecords() .WithID(AID); obj.SomeProperty = "Changed to new value"; _RepositoryA.UpdateRecord(obj); _unitOfWork.Save(); } } Repository interface: public interface IRepositoryA { IQueryable<MyObject> GetRecords(); UpdateRecord(MyObject obj); } Repository LINQtoSQL implementation: public class LINQtoSQLRepositoryA : IRepositoryA { private MyDataContext _DBContext; public LINQtoSQLRepositoryA(IUnitOfWork AUnitOfWork) { _DBConext = AUnitOfWork as MyDataContext; } public IQueryable<MyObject> GetRecords() { return from records in _DBContext.MyTable select new MyObject { ID = records.ID, SomeProperty = records.SomeProperty } } public bool UpdateRecord(MyObject AObj) { MyTableRecord record = (from u in _DB.MyTable where u.ID == AObj.ID select u).SingleOrDefault(); if (record == null) { return false; } record.SomeProperty = AObj.SomePropery; return true; } } Unit of work interface: public interface IUnitOfWork { void Save(); } Unit of work implemented in data context extension. public partial class MyDataContext : DataContext, IUnitOfWork { public void Save() { SubmitChanges(); } } StructureMap registry: public class DataServiceRegistry : Registry { public DataServiceRegistry() { // Unit of work For<IUnitOfWork>() .HttpContextScoped() .TheDefault.Is.ConstructedBy(() => new MyDataContext()); // RepositoryA For<IRepositoryA>() .Singleton() .Use<LINQtoSQLRepositoryA>(); // RepositoryB For<IRepositoryB>() .Singleton() .Use<LINQtoSQLRepositoryB>(); } } My problem is that when I call PerformActionOnObject on my service object, the update never fires any SQL. I think this is because the datacontext in the UnitofWork object is different to the one in RepositoryA where the data is changed. So when the service calls Save() on it's IUnitOfWork, the underlying datacontext does not have any updated data so no update SQL is fired. Is there something I've done wrong in the StrutureMap registry setup? Or is there a more fundamental problem with the design? Many thanks.

    Read the article

  • Complex pattern replacement using PHP preg_replace function ignoring quoted strings

    - by Saiful
    Consider the following string: this is a STRING WHERE some keywords ARE available. 'i need TO format the KEYWORDS from the STRING' In the above string keywords are STRING and WHERE Now i need to get an output as follows: this is a <b>STRING</b> <b>WHERE</b> some keywords ARE available. 'i need TO format the KEYWORDS from the STRING' So that the html output will be like: this is a STRING WHERE some keywords ARE available. 'i need TO format the KEYWORDS from the STRING' Note that the keywords within a quoted ('...') string will be ignored. in the above example i ignored the STRING keyword within the quoted string. Please give a modified version of the following PHP script so that I can have my desired result as above : $patterns = array('/STRING/','/WHERE/'); $replaces = array('<b>STRING</b>', '<b>WHERE</b>'); $string = "this is a STRING WHERE some keywords ARE available. 'i need TO format the KEYWORDS from the STRING'"; preg_replace($patterns, $replaces, $string);

    Read the article

  • java - check if string ends with certain pattern

    - by The Learner
    I have string like: This.is.a.great.place.too.work. (or) This/is/a/great/place/too/work/ than my java program should give me that the sentence is valid and it has "work". if i Have : This.is.a.great.place.too.work.hahahha (or) This/is/a/great/place/too/work/hahahah Should not give me that there is a work in the sentance. so I am looking at java strings to find a word at the end of the sentance having . (or),(or)/ before it. How can I achieve that

    Read the article

  • Best Practice, objects design ASP.NET MVC

    - by DoomStone
    Hello Stackoverflow I have a code design question that have been torbeling me for a while, you see I’m doing a refactoring of my website Cosplay Denmark, a site where cospalyers can upload images of them self in their costumes. The original site was done in php, Zend MVC, but my refactoring is being done in ASP.NET MVC 2. If you take the site http://www.cosplaydanmark.dk/Costumes/ (You can switch to English in the left column (Sprog)) Here you see a list of all the anime’s we have on the site with images, we show the name, how many different characters and how many images there are under this anime. http://www.cosplaydanmark.dk/Costumes/Bleach If you click on an anime will you get a list of characters within the given anime which we have images in, here do we show the character name, how many galleries and how many images. http://www.cosplaydanmark.dk/Costumes/Bleach/Ichigo_Kurosaki/ If you click on the character name, will you get a list of the galleries under the given character in the given anime. Here we have some information about the gallery, such as image count. http://www.cosplaydanmark.dk/Costumes/Bleach/Ichigo_Kurosaki/Admi/ Should you click the gallery do you get a list of the images in the gallery. My database look like this at the moment. As you can might imagine there are a lot of different query’s to create the site, on the first site I need to do a select on the on the “animes” table and for each result, I need to do a count select on characters and galleries. My plan to create this will be one of the following Where the IList, would be a lazy load list. But I can’t decide what would be the best solution for this would be, also if there is a better way of doing this. My priority is to have good performance with a minimum lose of features and code upkeep. I’m using a service pattern with a linq to sql repository. My design is not absolute, I’m willing to change it if it could increase performance :D I hope that I have describe my question good enough for you to understand what I mean, but ask away if there are anything I have missed.

    Read the article

  • Does my use of the strategy pattern violate the fundamental MVC pattern in iOS?

    - by Goodsquirrel
    I'm about to use the 'strategy' pattern in my iOS app, but feel like my approach violates the somehow fundamental MVC pattern. My app is displaying visual "stories", and a Story consists (i.e. has @properties) of one Photo and one or more VisualEvent objects to represent e.g. animated circles or moving arrows on the photo. Each VisualEvent object therefore has a eventType @property, that might be e.g. kEventTypeCircle or kEventTypeArrow. All events have things in common, like a startTime @property, but differ in the way they are being drawn on the StoryPlayerView. Currently I'm trying to follow the MVC pattern and have a StoryPlayer object (my controller) that knows about both the model objects (like Story and all kinds of visual events) and the view object StoryPlayerView. To chose the right drawing code for each of the different visual event types, my StoryPlayer is using a switch statement. @implementation StoryPlayer // (...) - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { switch (event.eventType) { case kEventTypeCircle: [self showCircleEvent:event onStoryPlayerView:storyPlayerView]; break; case kEventTypeArrow: [self showArrowDrawingEvent:event onStoryPlayerView:storyPlayerView]; break; // (...) } But switch statements for type checking are bad design, aren't they? According to Uncle Bob they lead to tight coupling and can and should almost always be replaced by polymorphism. Having read about the "Strategy"-Pattern in Head First Design Patterns, I felt this was a great way to get rid of my switch statement. So I changed the design like this: All specialized visual event types are now subclasses of an abstract VisualEvent class that has a showOnStoryPlayerView: method. @interface VisualEvent : NSObject - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView; // abstract Each and every concrete subclass implements a concrete specialized version of this drawing behavior method. @implementation CircleVisualEvent - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView { [storyPlayerView drawCircleAtPoint:self.position color:self.color lineWidth:self.lineWidth radius:self.radius]; } The StoryPlayer now simply calls the same method on all types of events. @implementation StoryPlayer - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { [event showOnStoryPlayerView:storyPlayerView]; } The result seems to be great: I got rid of the switch statement, and if I ever have to add new types of VisualEvents in the future, I simply create new subclasses of VisualEvent. And I won't have to change anything in StoryPlayer. But of cause this approach violates the MVC pattern since now my model has to know about and depend on my view! Now my controller talks to my model and my model talks to the view calling methods on StoryPlayerView like drawCircleAtPoint:color:lineWidth:radius:. But this kind of calls should be controller code not model code, right?? Seems to me like I made things worse. I'm confused! Am I completely missing the point of the strategy pattern? Is there a better way to get rid of the switch statement without breaking model-view separation?

    Read the article

  • The Dispose Pattern (and FxCop warnings)

    - by Scott Dorman
    [This is actually a response to Bill’s blog post, but since it isn’t possible to leave this as a comment on his blog it’s a post here.] There are many different ways to implement the Dispose pattern correctly. Some are (in my opinion) better than others. In Bill’s blog post he presents a particular pattern, which is an excerpt from his book (Effective C#). The issue centers around the fact that a reader took the code sample presented in the book and ran FxCop (Code Analysis) on it, which generated a warning: “Ensure that base.Dispose() is always called.” The “lesson learned” that Bill presents is that “tools are there to help us, not control us.” While I completely agree with the belief that tools are there to help us, I think it’s important to understand why FxCop is raising this particular warning. The code presented in Bill’s book looks like: // Have its own disposed flag.private bool disposed = false;protected override void Dispose(bool isDisposing){ // Don't dispose more than once. if (disposed) return; if (isDisposing) { // TODO: free managed resources here. } // TODO: free unmanaged resources here. // Let the base class free its resources. // Base class is responsible for calling // GC.SuppressFinalize( ) base.Dispose(isDisposing); // Set derived class disposed flag: disposed = true;} This code does follow all of the guidelines for implementing the Dispose pattern. In this case, it’s presumably part of a larger example showing how to implement the pattern as part of a base class. The reason FxCop is warning you about this code is the first if statement in the Dispose method, which will cause the method to exit if disposed is true. The problem here is that there is the possibility that if the disposed flag is true, the call to base.Dispose() will never be executed. As Bill points out, it is possible for some other code elsewhere in the class to set this flag. He states that this is an “unlikely occurrence.” While that is probably true, it can be a potentially dangerous assumption to make and is one that can be easily corrected. By changing the code slightly you can remove this assumption and correct the FxCop violation. private bool disposed = false;protected override void Dispose(bool disposing){ if (!disposed) { if (disposing) { // Dispose managed resources. } // Dispose unmanaged resources. disposed = true; } base.Dispose(disposing);} Using this implementation allows the call to base.Dispose() to always occur, which ensures that the the disposal chain is always properly followed. Technorati Tags: .NET,C#,Dispose Pattern

    Read the article

  • Pattern for Accessing MySQL connection

    - by Dipan Mehta
    We have an application which is C++ trying to access MySQL database. There are several (about 5 or so) threads in the application (with Boost library for threading) and in each thread has a few objects, each of which is trying to access Database for its' own purpose. It has a simple ORM kind of model but that really is not an important factor here. There are three potential access patterns i can think of: There could be single connection object per application or thread and is shared between all (or group). The object needs to be thread safe and there will be contentions but MySQL will not be fired with too many connections. Every object could initiate connection on its own. The database needs to take care of concurrency (which i think MySQL can) and the design could be much simpler. There could be two possibilities here. a. either object keeps a persistent connection for its life OR b. object initiate connection as and when needed. To simplify the contention as in case of 1 and not to create too many sockets as in case of 2, we can have group/set based connections. So there could be there could be more than one connection (say N), each of this connection could be shared connection across M objects. Naturally, each of the pattern has different resource cost and would work under different constraints and objectives. What criteria should i use to choose the pattern of this for my own application? What are some of the advantages and disadvantages of each of these pattern over the other? Are there any other pattern which is better? PS: I have been through these questions: mysql, one connection vs multiple and MySQL with mutiple threads and processes But they don't quite answer exactly what i am trying to ask.

    Read the article

  • Using visitor pattern with large object hierarchy

    - by T. Fabre
    Context I've been using with a hierarchy of objects (an expression tree) a "pseudo" visitor pattern (pseudo, as in it does not use double dispatch) : public interface MyInterface { void Accept(SomeClass operationClass); } public class MyImpl : MyInterface { public void Accept(SomeClass operationClass) { operationClass.DoSomething(); operationClass.DoSomethingElse(); // ... and so on ... } } This design was, however questionnable, pretty comfortable since the number of implementations of MyInterface is significant (~50 or more) and I didn't need to add extra operations. Each implementation is unique (it's a different expression or operator), and some are composites (ie, operator nodes that will contain other operator/leaf nodes). Traversal is currently performed by calling the Accept operation on the root node of the tree, which in turns calls Accept on each of its child nodes, which in turn... and so on... But the time has come where I need to add a new operation, such as pretty printing : public class MyImpl : MyInterface { // Property does not come from MyInterface public string SomeProperty { get; set; } public void Accept(SomeClass operationClass) { operationClass.DoSomething(); operationClass.DoSomethingElse(); // ... and so on ... } public void Accept(SomePrettyPrinter printer) { printer.PrettyPrint(this.SomeProperty); } } I basically see two options : Keep the same design, adding a new method for my operation to each derived class, at the expense of maintainibility (not an option, IMHO) Use the "true" Visitor pattern, at the expense of extensibility (not an option, as I expect to have more implementations coming along the way...), with about 50+ overloads of the Visit method, each one matching a specific implementation ? Question Would you recommand using the Visitor pattern ? Is there any other pattern that could help solve this issue ?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >