Search Results

Search found 6142 results on 246 pages for 'singleton pattern'.

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

  • Are Promises/A a good event design pattern to implement even in synchronous languages like PHP?

    - by Xeoncross
    I have always kept an eye out for event systems when writing code in scripting languages. Web applications have a history of allowing the user to add plugins and modules whenever needed. In most PHP systems you have a global/singleton event object which all interested parties tie into and wait to be alerted to changes. Event::on('event_name', $callback); Recently more patterns like the observer have been used for things like jQuery. $(el).on('event', callback); Even PHP now has built in classes for it. class Blog extends SplSubject { public function save() { $this->notify(); } } Anyway, the Promises/A proposal has caught my eye. It is designed for asynchronous systems, but I'm wondering if it is also a good design to implement now that even synchronous languages like PHP are changing. Combining Dependency Injection with Promises/A seems it might be the best combination for handling events currently.

    Read the article

  • Hide or Show singleton?

    - by Sinker
    Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such: C#: MyClass.Instance Java: MyClass.getInstance() The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible? Here are the alternatives for illustrative purposes: Exposed(C#): private static MyClass instance; public static MyClass Instance { get { if (instance == null) instance = new MyClass(); return instance; } } public void PerformOperation() { ... } Hidden (C#): private static MyClass instance; public static void PerformOperation() { if (instance == null) { instance = new MyClass(); } ... } EDIT: There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario: My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger class (e.g. Logger.Instance.Warn(...) or Logger.Instance.Error(...) etc. Should I use Logger.Warn(...) or Logger.Warn(...) instead? If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :)

    Read the article

  • Repository pattern - Switch out the database and switch in XML files

    - by glasto red
    Repository pattern - Switch out the database and switch in XML files. Hello I have an asp.net MVC 2.0 project and I have followed the Repository pattern. Periodically, I am losing access to the database server so I want to have another mechanism in place (XML files) to continue developing. It is not possible to have a local version of the db unfortunately! I thought this would be relatively easy using the Repository pattern, to switch out the db repositories and switch in XML versions. However, I am having real trouble coming up with a solution. I have tried LinqToXML but then ran into problems trying to return a List of News items as the LinqToXML ToList returns Generic.List Should I be mapping the XElement list over to the News list by hand? It just seems a bit clunky compared to LinqToSQL attributes on the News class and then simply doing a Table.....ToList(); Any direction would be appreciated. Thanks

    Read the article

  • Scala wont pattern match with java.lang.String and Case Class

    - by Stefan
    Hello fellow Scala Programmers I have been working with Scala for some month now, however I have a problem with some properly basic stuff, I am hoping you will help my out with it. case class PersonClass(name: String, age: Int) object CaseTester { def main(args:Array[String]) { val string = "hej" string match { case e:String => println(string) case PersonClass => println(string) } } } When I am doing like this I get error: pattern type is incompatible with expected type; found : object PersonClass required: java.lang.String case PersonClass = println(string) And if I then change the second line in the pattern matching to the following: case e:PersonClass => println(string) I then get the error: error: scrutinee is incompatible with pattern type; found : PersonClass required: java.lang.String case e:PersonClass = println(string) However if I change the string definition to the following it compiles fine in both cases. val string:AnyRef = "hej"

    Read the article

  • Mapping to a JSON method with url-pattern

    - by Brian
    I'm creating a Spring MVC application that will have a controller with 'RequestMapping'-annotated methods, including a JSON method. It currently has static content that resides in webapps/static, and the app itself resides in webapps/myapp. I assume that Catalina's default servlet is handling the static content, and my *.htm url-pattern in web.xml is returning the request for my JSP page, but I haven't been able to get the JSON method to be called. How do I write the url-pattern in the servlet mapping to do so? Using /* has not worked; it prevents the app from being accessed at all. Is there anything else to be aware of? EDIT: The url-pattern '/' appears to allow the JSON request through, because a 406 error is returned. What then would need to be modified to allow JSON to be returned?

    Read the article

  • Using the Module Pattern for larger projects

    - by Rob
    I'm interested in using the Module Pattern to better organize my future projects. Unfortunately, there are only a few brief tutorials and proof-of-concept examples of the Module Pattern. Using the module pattern, I would like to organize projects into this sort of structure: project.arm.object.method(); Where "project" is my global project name, "arm" is a sub-section or branch of the project, "object" is an individual object, and so on to the methods and properties. However, I'm not sure how I should be declaring and organizing multiple "arms" and "objects" under "project". var project = window.project || {}; project.arm = project.arm || {}; project.arm.object = (function() { var privateVar = "Private contents."; function privateMethod() { alert(privateVar); } return { method: privateMethod }; }()); Are there any best practices or conventions when defining a complex module structure? Should I just declare a new arm/object underneath the last?

    Read the article

  • Javascript: Using the Module Pattern for larger projects

    - by Rob
    I'm interested in using the Module Pattern to better organize my future projects. Unfortunately, there are only a few brief tutorials and proof-of-concept examples of the Module Pattern. Using the module pattern, I would like to organize projects into this sort of structure: project.arm.object.method(); Where "project" is my global project name, "arm" is a sub-section or branch of the project, "object" is an individual object, and so on to the methods and properties. However, I'm not sure how I should be declaring and organizing multiple "arms" and "objects" under "project". var project = window.project || {}; project.arm = project.arm || {}; project.arm.object = (function() { var privateVar = "Private contents."; function privateMethod() { alert(privateVar); } return { method: privateMethod }; }()); Are there any best practices or conventions when defining a complex module structure? Should I just declare a new arm/object underneath the last?

    Read the article

  • Is it possible, with simple F# pattern matching transformations, to ignore unmatched values without

    - by Phobis
    So, I previously asked this question: http://stackoverflow.com/questions/2820234/can-someone-help-me-compare-using-f-over-c-in-this-specific-example-ip-address I was looking at the posted code and I was wondering if this code could be written without it producing a warning: let [|a;b;c;d|] = s.Split [|'.'|] IP(parseOrParts a, parseOrParts b, parseOrParts c, parseOrParts d) Is it possible to do something for the match _ pattern ot ignore? Without adding in something like Active Patterns? i want to keep the code as simple as possible... can I do this without drastically changing this code? NOTE: Warning is as follows Warning Incomplete pattern matches on this expression. For example, the value '[|_; _; _; _; _|]' may indicate a case not covered by the pattern(s).

    Read the article

  • What is this Design Pattern?

    - by Can't Tell
    I read the Wikipedia articles on FactoryMethod and AbstractFactory but the following code doesn't seem to fit anywhere. Can someone explain to me what the following pattern is or if it is an anti-pattern? interace PaymentGateway{ void makePayment(); } class PaypalPaymentGateway implements PaymentGateway { public void makePayment() { //some implementation } } class AuthorizeNetPaymentGateway implements PaymentGateway { public void makePayment() { //some implementation } } class PaymentGatewayFacotry{ PaymentGateway createPaymentGateway(int gatewayId) { if(gatewayId == 1) return PaypalPaymentGateway(); else if(gatewayId == 2) return AuthorizeNetPaymentGateway(); } } Let's say the user selects the payment method using a radio button on an html page and the gatewayId is derived from the radio button value. I have seen code like this and thought it was the AbstractFactory pattern but after reading the Wikipedia article, I'm having doubts.

    Read the article

  • Is the Observer pattern adequate for this kind of scenario?

    - by Omega
    I'm creating a simple game development framework with Ruby. There is a node system. A node is a game entity, and it has position. It can have children nodes (and one parent node). Children are always drawn relatively to their parent. Nodes have a @position field. Anyone can modify it. When such position is modified, the node must update its children accordingly to properly draw them relatively to it. @position contains a Point instance (a class with x and y properties, plus some other useful methods). I need to know when a node's @position's state changes, so I can tell the node to update its children. This is easy if the programmer does something like this: @node.position = Point.new(300,300) Because it is equivalent to calling this: # Code in the Node class def position=(newValue) @position = newValue update_my_children # <--- I know that the position changed end But, I'm lost when this happens: @node.position.x = 300 The only one that knows that the position changed is the Point instance stored in the @position property of the node. But I need the node to be notified! It was at this point that I considered the Observer pattern. Basically, Point is now observable. When a node's position property is given a new Point instance (through the assignment operator), it will stop observing the previous Point it had (if any), and start observing the new one. When a Point instance gets a state change, all observers (the node owning it) will be notified, so now my node can update its children when the position changes. A problem is when this happens: @someNode.position = @anotherNode.position This means that two nodes are observing the same point. If I change one of the node's position, the other would change as well. To fix this, when a position is assigned, I plan to create a new Point instance, copy the passed argument's x and y, and store my newly created point instead of storing the passed one. Another problem I fear is this: somePoint = @node.position somePoint.x = 500 This would, technically, modify @node's position. I'm not sure if anyone would be expecting that behavior. I'm under the impression that people see Point as some kind of primitive rather than an actual object. Is this approach even reasonable? Reasons I'm feeling skeptical: I've heard that the Observer pattern should be used with, well, many observers. Technically, in this scenario there is only one observer at a time. When assigning a node's position as another's (@someNode.position = @anotherNode.position), where I create a whole new instance rather than storing the passed point, it feels hackish, or even inefficient.

    Read the article

  • OOW content for Pattern Matching....

    - by KLaker
    If you missed my sessions at OpenWorld then don't worry - all the content we used for pattern matching (presentation and hands-on lab) is now available for download. My presentation "SQL: The Best Development Language for Big Data?" is available for download from the OOW Content Catalog, see here: https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=9101 For the hands-on lab ("Pattern Matching at the Speed of Thought with Oracle Database 12c") we used the Oracle-By-Example content. The OOW hands-on lab uses Oracle Database 12c Release 1 (12.1) and uses the MATCH_RECOGNIZE clause to perform some basic pattern matching examples in SQL. This lab is broken down into four main steps: Logically partition and order the data that is used in the MATCH_RECOGNIZE clause with its PARTITION BY and ORDER BY clauses. Define patterns of rows to seek using the PATTERN clause of the MATCH_RECOGNIZE clause. These patterns use regular expressions syntax, a powerful and expressive feature, applied to the pattern variables you define. Specify the logical conditions required to map a row to a row pattern variable in the DEFINE clause. Define measures, which are expressions usable in the MEASURES clause of the SQL query. You can download the setup files to build the ticker schema and the student notes from the Oracle Learning Library. The direct link to the example on using pattern matching is here: http://apex.oracle.com/pls/apex/f?p=44785:24:0::NO:24:P24_CONTENT_ID,P24_PREV_PAGE:6781,2.

    Read the article

  • Observer pattern used with decorator pattern

    - by icelated
    I want to make a program that does an order entry system for beverages. ( i will probably do description, cost) I want to use the Decorator pattern and the observer pattern. I made a UML drawing and saved it as a pic for easy viewing. This site wont let me upload as a word doc so i have to upload a pic - i hope its easily viewable.... I need to know if i am doing the UML / design patterns correctly before moving on to the coding part. Beverage is my abstract component class. Espresso, houseblend, darkroast are my concrete subject classes.. I also have a condiment decorator class milk,mocha,soy,whip. would be my observer? because they would be interested in data changes to cost? Now, would the espresso,houseblend etc, be my SUBJECT and the condiments be my observer? My theory is that Cost is a changes and that the condiments need to know the changes? So, subject = esspresso,houseblend,darkroast,etc.. // they hold cost() Observer = milk,mocha,soy,whip? // they hold cost() would be the concrete components and the milk,mocha,soy,whip? would be the decorator! So, following good software engineering practices "design to an interface and not implementation" or "identify things that change from those that dont" would i need a costbehavior interface? If you look at the UML you will see where i am going with this and see if i am implementing observer + Decorator pattern correctly? I think the decorator is correct. since, the pic is not very viewable i will detail the classes here: Beverage class(register observer, remove observer, notify observer, description) these classes are the concrete beverage classes espresso, houseblend,darkroast, decaf(cost,getdescription,setcost,costchanged) interface observer class(update) // cost? interface costbehavior class(cost) // since this changes? condiment decorator class( getdescription) concrete classes that are linked to the 2 interface s and decorator are: milk,mocha,soy,whip(cost,getdescription,update) these are my decorator/ wrapper classes. Thank you.. Is there a way to make this picture bigger?

    Read the article

  • Singleton Properties

    - by coffeeaddict
    Ok, if I create a singleton class and expose the singleton object through a public static property...I understand that. But my singleton class has other properties in it. Should those be static? Should those also be private? I just want to be able to access all properties of my singleton class by doing this: MySingletonClass.SingletonProperty.SomeProperty2 Where SingletonProperty returns me the single singleton instance. I guess my question is, how do you expose the other properties in the singleton class..make them private and then access them through your public singleton static property?

    Read the article

  • How to bind a control to a singleton in Cocoa?

    - by SphereCat1
    I have a singleton in my FTP app designed to store all of the types of servers that the app can handle, such as FTP or Amazon S3. These types are plugins which are located in the app bundle. Their path is located by applicationWillFinishLoading: and sent to the addServerType: method inside the singleton to be loaded and stored in an NSMutableDictionary. My question is this: How do I bind an NSDictionaryController to the dictionary inside the singleton instance? Can it be done in IB, or do I have to do it in code? I need to be able to display the dictionary's keys in an NSPopupButton so the user can select a server type. Thanks in advance! SphereCat1

    Read the article

  • Do I still have to implement a singleton class by hand in .net, even when using .Net4.0?

    - by Hamish Grubijan
    Once the singleton pattern is understood, writing subsequent singleton classes in C# is a brainless exercise. I would hope that the framework would help you by providing an interface or a base class to do that. Here is how I envision it: public sealed class Schablone : ISingleton<Schablone> { // Stuff forced by the interface goes here // Extra logic goes here } Does what I am looking for exist? Is there some syntactic sugar for constructing a singleton class - whether with an interface, a class attribute, etc.? Can one write a useful and bullet-proof ISingleton themselves? Care to try? Thanks!

    Read the article

  • Is this a valid, lazy, thread-safe Singleton implementation for C#?

    - by Matthew
    I implemented a Singleton pattern like this: public sealed class MyClass { ... public static MyClass Instance { get { return SingletonHolder.instance; } } ... static class SingletonHolder { public static MyClass instance = new MyClass (); } } From Googling around for C# Singleton implementations, it doesn't seem like this is a common way to do things in C#. I found one similar implementation, but the SingletonHolder class wasn't static, and included an explicit (empty) static constructor. Is this a valid, lazy, thread-safe way to implement the Singleton pattern? Or is there something I'm missing?

    Read the article

  • EF Query Object Pattern over Repository Example

    - by Dale Burrell
    I have built a repository which only exposes IEnumerable based mostly on the examples in "Professional ASP.NET Design Patterns" by Scott Millett. However because he mostly uses NHibernate his example of how to implement the Query Object Pattern, or rather how to best translate the query into something useful in EF, is a bit lacking. I am looking for a good example of an implementation of the Query Object Pattern using EF4.

    Read the article

  • Count number of occurrences of a pattern in a file (even on same line)

    - by jrdioko
    When searching for number of occurrences of a string in a file, I generally use: grep pattern file | wc -l However, this only finds one occurrence per line, because of the way grep works. How can I search for the number of times a string appears in a file, regardless of whether they are on the same or different lines? Also, what if I'm searching for a regex pattern, not a simple string? How can I count those, or, even better, print each match on a new line?

    Read the article

  • Aggregate Pattern and Performance Issues

    - by Mosh
    Hello, I have read about the Aggregate Pattern but I'm confused about something here. The pattern states that all the objects belonging to the aggregate should be accessed via the Aggregate Root, and not directly. And I'm assuming that is the reason why they say you should have a single Repository per Aggregate. But I think this adds a noticeable overhead to the application. For example, in a typical Web-based application, what if I want to get an object belonging to an aggregate (which is NOT the aggregate root)? I'll have to call Repository.GetAggregateRootObject(), which loads the aggregate root and all its child objects, and then iterate through the child objects to find the one I'm looking for. In other words, I'm loading lots of data and throwing them out except the particular object I'm looking for. Is there something I'm missing here? PS: I know some of you may suggest that we can improve performance with Lazy Loading. But that's not what I'm asking here... The aggregate pattern requires that all objects belonging to the aggregate be loaded together, so we can enforce business rules.

    Read the article

  • Visitor Pattern can be replaced with Callback functions?

    - by getit
    Is there any significant benefit to using either technique? In case there are variations, the Visitor Pattern I mean is this: http://en.wikipedia.org/wiki/Visitor_pattern And below is an example of using a delegate to achieve the same effect (at least I think it is the same) Say there is a collection of nested elements: Schools contain Departments which contain Students Instead of using the Visitor pattern to perform something on each collection item, why not use a simple callback (Action delegate in C#) Say something like this class Department { List Students; } class School { List Departments; VisitStudents(Action<Student> actionDelegate) { foreach(var dep in this.Departments) { foreach(var stu in dep.Students) { actionDelegate(stu); } } } } School A = new School(); ...//populate collections A.Visit((student)=> { ...Do Something with student... }); *EDIT Example with delegate accepting multiple params Say I wanted to pass both the student and department, I could modify the Action definition like so: Action class School { List Departments; VisitStudents(Action<Student, Department> actionDelegate, Action<Department> d2) { foreach(var dep in this.Departments) { d2(dep); //This performs a different process. //Using Visitor pattern would avoid having to keep adding new delegates. //This looks like the main benefit so far foreach(var stu in dep.Students) { actionDelegate(stu, dep); } } } }

    Read the article

  • Is there any reason for an object pool to not be treated as a singleton?

    - by Chris Charabaruk
    I don't necessarily mean implemented using the singleton pattern, but rather, only having and using one instance of a pool. I don't like the idea of having just one pool (or one per pooled type). However, I can't really come up with any concrete situations where there's an advantage to multiple pools for mutable types, at least not any where a single pool can function just as well. What advantages are there to having multiple pools over a singleton pool?

    Read the article

  • Could a singleton type replace static methods and classes?

    - by MKO
    In C# Static methods has long served a purpose allowing us to call them without instantiating classes. Only in later year have we became more aware of the problems of using static methods and classes. They can’t use interfaces They can’t use inheritance They are hard to test because you can’t make mocks and stubs Is there a better way ? Obviously we need to be able to access library methods without instantiated classes all the time otherwise our code would become pretty cluttered One possibly solution is to use a new keyword for an old concept: the singleton. Singleton’s are global instances of a class, since they are instances we can use them as we would normal classes. In order to make their use nice and practical we'd need some syntactic sugar however Say that the Math class would be of type singleton instead of an actual class. The actual class containing all the default methods for the Math singleton is DefaultMath, which implements the interface IMath. The singleton would be declared as singleton Math : IMath { public Math { this = new DefaultMath(); } } If we wanted to substitute our own class for all math operations we could make a new class MyMath that inherits DefaultMath, or we could just inherit from the interface IMath and create a whole new Class. To make our class the active Math class, you'd do a simple assignment Math = new MyMath(); and voilá! the next time we call Math.Floor it will call your method. Note that for a normal singleton we'd have to write something like Math.Instance.Floor but the compiler eliminates the need for the Instance property Another idea would be to be able to define a singletons as Lazy so they get instantiated only when they're first called, like lazy singleton Math : IMath What do you think, would it have been a better solution that static methods and classes? Is there any problems with this approach?

    Read the article

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