Search Results

Search found 5705 results on 229 pages for 'observer pattern'.

Page 1/229 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • A talk about observer pattern

    - by Martin
    As part of a university course I'm taking, I have to hold a 10 minute talk about the observer pattern. So far these are my points: What is it? (defenition) Polling is an alternative Polling VS Observer When Observer is better When Polling is better (taken from here) A statement that Mediator pattern is worth checking out. (I won't have time to cover it in 10 minutes) I would be happy to hear about: Any suggestions to add something? Another alternative (if exists)

    Read the article

  • Adding an observer to UIImageView? observer & notifications

    - by sagar
    Each class has almost one method named addObserver [imgVURL addObserver:<#(NSObject *)observer#> forKeyPath:<#(NSString *)keyPath#> options:<#(NSKeyValueObservingOptions)options#> context:<#(void *)context#>] Here, imgVURL is an image which is going to be load an image asynchronously. When image will be loaded dynamically - other class will set an image from loaded data. Now, my question is how can we add an observer to UIImageView's instance. Observer and notifications are same or not ? If it is not then what's different ? Let's have some sample code That I did in my project to understand my question. // locating image view from Scroll view by it's tag imgVURL=(UIImageView*)[scrMain viewWithTag:(kTagImagesTag+i)]; // ImageViewURL is a class which contains methods of // didReceiveResponse // didReceiveData // connection ImageViewURL *tmp=[[ImageViewURL alloc] init]; // it has a nonatomic property which will take the reference of my image view tmp.imgV=imgVURL; // now I will pass a url from my an array to property strURL // in strUrl I have custom setter // in which I am initializing a connection tmp.strUrl=[NSURL URLWithString:[[tblmain objectAtIndex:i] valueForKey:@"url"]]; // from ImageViewURL.m file -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // NSLog@"ImageView Ref From - %@",imgV); // see imgV has reference of my -> imgVURL (nonatomic,assign) imgV.image=[UIImage imageWithData:myWebData]; [connection release]; connection=nil; } // as you can see in above code many many images are loaded asynchronously // now How can I add an observer to an imageview whether it received or not.

    Read the article

  • Observer pattern for unpredictable observation time

    - by JoJo
    I have a situation where objects are created at unpredictable times. Some of these objects are created before an important event, some after. If the event already happened, I make the object execute stuff right away. If the event is forthcoming, I make the object observe the event. When the event triggers, the object is notified and executes the same code. if (subject.eventAlreadyHappened()) { observer.executeStuff(); } else { subject.subscribe(observer); } Is there another design pattern to wrap or even replace this observer pattern? I think it looks a little dirty to me.

    Read the article

  • What are the advantages of the delegate pattern over the observer pattern?

    - by JoJo
    In the delegate pattern, only one object can directly listen to another object's events. In the observer pattern, any number of objects can listen to a particular object's events. When designing a class that needs to notify other object(s) of events, why would you ever use the delegate pattern over the observer pattern? I see the observer pattern as more flexible. You may only have one observer now, but a future design may require multiple observers.

    Read the article

  • The Template Method Design Pattern using C# .Net

    - by nijhawan.saurabh
    First of all I'll just put this pattern in context and describe its intent as in the GOF book:   Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to Subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the Algorithm's Structure.    Usage: When you are certain about the High Level steps involved in an Algorithm/Work flow you can use the Template Pattern which allows the Base Class to define the Sequence of the Steps but permits the Sub classes to alter the implementation of any/all steps.   Example in the .Net framework: The most common example is the Asp.Net Page Life Cycle. The Page Life Cycle has a few methods which are called in a sequence but we have the liberty to modify the functionality of any of the methods by overriding them.   Sample implementation of Template Method Pattern:   Let's see the class diagram first:            Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}   And here goes the code:EmailBase.cs     1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public abstract class EmailBase    10     {    11     12         public bool SendEmail()    13         {    14             if (CheckEmailAddress() == true) // Method1 in the sequence    15             {    16                 if (ValidateMessage() == true) // Method2 in the sequence    17                 {    18                     if (SendMail() == true) // Method3 in the sequence    19                     {    20                         return true;    21                     }    22                     else    23                     {    24                         return false;    25                     }    26     27                 }    28                 else    29                 {    30                     return false;    31                 }    32     33             }    34             else    35             {    36                 return false;    37     38             }    39     40     41         }    42     43         protected abstract bool CheckEmailAddress();    44         protected abstract bool ValidateMessage();    45         protected abstract bool SendMail();    46     47     48     }    49 }    50    EmailYahoo.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailYahoo:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : YahooEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : YahooEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : YahooEmail");    27             return true;    28         }    29     30     31     }    32 }    33   EmailGoogle.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailGoogle:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : GoogleEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : GoogleEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : GoogleEmail");    27             return true;    28         }    29     30     31     }    32 }    33   Program.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     class Program    10     {    11         static void Main(string[] args)    12         {    13             Console.WriteLine("Please choose an Email Account to send an Email:");    14             Console.WriteLine("Choose 1 for Google");    15             Console.WriteLine("Choose 2 for Yahoo");    16             string choice = Console.ReadLine();    17     18             if (choice == "1")    19             {    20                 EmailBase email = new EmailGoogle(); // Rather than newing it up here, you may use a factory to do so.    21                 email.SendEmail();    22     23             }    24             if (choice == "2")    25             {    26                 EmailBase email = new EmailYahoo(); // Rather than newing it up here, you may use a factory to do so.    27                 email.SendEmail();    28             }    29         }    30     }    31 }    32    Final Words: It's very obvious that why the Template Method Pattern is a popular pattern, everything at last revolves around Algorithms and if you are clear with the steps involved it makes real sense to delegate the duty of implementing the step's functionality to the sub classes. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}

    Read the article

  • General Overview of Design Pattern Types

    Typically most software engineering design patterns fall into one of three categories in regards to types. Three types of software design patterns include: Creational Type Patterns Structural Type Patterns Behavioral Type Patterns The Creational Pattern type is geared toward defining the preferred methods for creating new instances of objects. An example of this type is the Singleton Pattern. The Singleton Pattern can be used if an application only needs one instance of a class. In addition, this singular instance also needs to be accessible across an application. The benefit of the Singleton Pattern is that you control both instantiation and access using this pattern. The Structural Pattern type is a way to describe the hierarchy of objects and classes so that they can be consolidated into a larger structure. An example of this type is the Façade Pattern.  The Façade Pattern is used to define a base interface so that all other interfaces inherit from the parent interface. This can be used to simplify a number of similar object interactions into one single standard interface. The Behavioral Pattern Type deals with communication between objects. An example of this type is the State Design Pattern. The State Design Pattern enables objects to alter functionality and processing based on the internal state of the object at a given time.

    Read the article

  • Is there a design pattern for chained observers?

    - by sharakan
    Several times, I've found myself in a situation where I want to add functionality to an existing Observer-Observable relationship. For example, let's say I have an Observable class called PriceFeed, instances of which are created by a variety of PriceSources. Observers on this are notified whenever the underlying PriceSource updates the PriceFeed with a new price. Now I want to add a feature that allows a (temporary) override to be set on the PriceFeed. The PriceSource should still update prices on the PriceFeed, but for as long as the override is set, whenever a consumer asks PriceFeed for it's current value, it should get the override. The way I did this was to introduce a new OverrideablePriceFeed that is itself both an Observer and an Observable, and that decorates the actual PriceFeed. It's implementation of .getPrice() is straight from Chain of Responsibility, but how about the handling of Observable events? When an override is set or cleared, it should issue it's own event to Observers, as well as forwarding events from the underlying PriceFeed. I think of this as some kind of a chained observer, and was curious if there's a more definitive description of a similar pattern.

    Read the article

  • Using an observer within an Engine

    - by Tim
    I've created an Engine which is basically used for all of our projects. Now what I want to do is add a before_create callback to all of the models in this Engine. After some searching I found out that an observer is the way to go. So, I've created this observer: class AuthObserver < ActiveRecord::Observer def before_create( record ) p record end end And now I need to add it to the application, but of course in my Engine there is no such file as application.rb. What I tried is adding it to an initializer located in /config/initializers/observers.rb Like so: Rails.application.config.active_record.observers = :auth_observer But this doesn't work, and it throws no errors. Anybody out here has experience using an observer inside an engine? Thanks a lot!

    Read the article

  • iPhone Key-Value Observer: observer not registering in UITableViewController

    - by Scott
    Hi Fellow iPhone Developers, I am an experienced software engineer but new to the iPhone platform. I have successfully implemented sub-classed view controllers and can push and pop parent/child views on the view controller stack. However, I have struck trouble while trying to update a view controller when an object is edited in a child view controller. After much failed experimentation, I discovered the key-value observer API which looked like the perfect way to do this. I then registered an observer in my main/parent view controller, and in the observer I intend to reload the view. The idea is that when the object is edited in the child view controller, this will be fired. However, I think that the observer is not being registered, because I know that the value is being updated in the editing view controller (I can see it in the debugger), but the observing method is never being called. Please help! Code snippets follow below. Object being observed. I believe that this is key-value compliant as the value is set when called with the setvalue message (see Child View Controller below). X.h: @interface X : NSObject <NSCoding> { NSString *name; ... @property (nonatomic, retain) NSString *name; X.m: @implementation X @synthesize name; ... Main View Controller.h: @class X; @interface XViewController : UITableViewController { X *x; ... Main View Controller.m: @implementation XViewController @synthesize x; ... - (void)viewDidLoad { ... [self.x addObserver:self forKeyPath: @"name" options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil]; [super viewDidLoad]; } ... - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqual:@"name"]) { NSLog(@"Found change to X"); [self.tableView reloadData]; } [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } Child View Controller.m: (this correctly sets the value in the object in the child view controller) [self.x setValue:[[tempValues objectForKey:key] text] forKey:@"name"];

    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

  • Optimal communication pattern to update subscribers

    - by hpc
    What is the optimal way to update the subscriber's local model on changes C on a central model M? ( M + C - M_c) The update can be done by the following methods: Publish the updated model M_c to all subscribers. Drawback: if the model is big in contrast to the change it results in much more data to be communicated. Publish change C to all subscribes. The subscribers will then update their local model in the same way as the server does. Drawback: The client needs to know the business logic to update the model in the same way as the server. It must be assured that the subscribed model stays equal to the central model. Calculate the delta (or patch) of the change (M_c - M = D_c) and transfer the delta. Drawback: This requires that calculating and applying the delta (M + D_c = M_c) is an cheap/easy operation. If a client newly subscribes it must be initialized. This involves sending the current model M. So method 1 is always required. Think of playing chess as a concrete example: Subscribers send moves and want to see the latest chess board state. The server checks validity of the move and applies it to the chess board. The server can then send the updated chessboard (method 1) or just send the move (method 2) or send the delta (method 3): remove piece on field D4, put tower on field D8.

    Read the article

  • Is DataAdapter use facade pattern or Adapter pattern.

    - by Krirk
    When i see Update(),Fill() method of DataAdapter object I always think Is DataAdapter use facade pattern ? It looks like behind the scenes It will create Command object, Connection object and execute it for us. Or DataAdapter use Adapter pattern because it is adapter between Dataset and Comamand object ,Connection object ?

    Read the article

  • Design pattern for cost calculator app?

    - by Anders Svensson
    Hi, I have a problem that I’ve tried to get help for before, but I wasn’t able to solve it then, so I’m trying to simplify the problem now to see if I can get some more concrete help with this because it is driving me crazy… Basically, I have a working (more complex) version of this application, which is a project cost calculator. But because I am at the same time trying to learn to design my applications better, I would like some input on how I could improve this design. Basically the main thing I want is input on the conditionals that (here) appear repeated in two places. The suggestions I got before was to use the strategy pattern or factory pattern. I also know about the Martin Fowler book with the suggestion to Refactor conditional with polymorphism. I understand that principle in his simpler example. But how can I do either of these things here (if any would be suitable)? The way I see it, the calculation is dependent on a couple of conditions: 1. What kind of service is it, writing or analysis? 2. Is the project small, medium or large? (Please note that there may be other parameters as well, equally different, such as “are the products new or previously existing?” So such parameters should be possible to add, but I tried to keep the example simple with only two parameters to be able to get concrete help) So refactoring with polymorphism would imply creating a number of subclasses, which I already have for the first condition (type of service), and should I really create more subclasses for the second condition as well (size)? What would that become, AnalysisSmall, AnalysisMedium, AnalysisLarge, WritingSmall, etc…??? No, I know that’s not good, I just don’t see how to work with that pattern anyway else? I see the same problem basically for the suggestions of using the strategy pattern (and the factory pattern as I see it would just be a helper to achieve the polymorphism above). So please, if anyone has concrete suggestions as to how to design these classes the best way I would be really grateful! Please also consider whether I have chosen the objects correctly too, or if they need to be redesigned. (Responses like "you should consider the factory pattern" will obviously not be helpful... I've already been down that road and I'm stumped at precisely how in this case) Regards, Anders The code (very simplified, don’t mind the fact that I’m using strings instead of enums, not using a config file for data etc, that will be done as necessary in the real application once I get the hang of these design problems): public abstract class Service { protected Dictionary<string, int> _hours; protected const int SMALL = 2; protected const int MEDIUM = 8; public int NumberOfProducts { get; set; } public abstract int GetHours(); } public class Writing : Service { public Writing(int numberOfProducts) { NumberOfProducts = numberOfProducts; _hours = new Dictionary<string, int> { { "small", 125 }, { "medium", 100 }, { "large", 60 } }; } public override int GetHours() { if (NumberOfProducts <= SMALL) return _hours["small"] * NumberOfProducts; if (NumberOfProducts <= MEDIUM) return (_hours["small"] * SMALL) + (_hours["medium"] * (NumberOfProducts - SMALL)); return (_hours["small"] * SMALL) + (_hours["medium"] * (MEDIUM - SMALL)) + (_hours["large"] * (NumberOfProducts - MEDIUM)); } } public class Analysis : Service { public Analysis(int numberOfProducts) { NumberOfProducts = numberOfProducts; _hours = new Dictionary<string, int> { { "small", 56 }, { "medium", 104 }, { "large", 200 } }; } public override int GetHours() { if (NumberOfProducts <= SMALL) return _hours["small"]; if (NumberOfProducts <= MEDIUM) return _hours["medium"]; return _hours["large"]; } } public partial class Form1 : Form { public Form1() { InitializeComponent(); List<int> quantities = new List<int>(); for (int i = 0; i < 100; i++) { quantities.Add(i); } comboBoxNumberOfProducts.DataSource = quantities; } private void comboBoxNumberOfProducts_SelectedIndexChanged(object sender, EventArgs e) { Service writing = new Writing((int) comboBoxNumberOfProducts.SelectedItem); Service analysis = new Analysis((int) comboBoxNumberOfProducts.SelectedItem); labelWriterHours.Text = writing.GetHours().ToString(); labelAnalysisHours.Text = analysis.GetHours().ToString(); } }

    Read the article

  • A couple of pattern matching issues with pattern matching in Lua

    - by Josh
    I'm fairly new to lua programming, but I'm also a quick study. I've been working on a weather forecaster for a program that I use, and it's working well, for the most part. Here is what I have so far. (Pay no attention to the zs.stuff. That is program specific and has no bearing on the lua coding.) if not http then http = require("socket.http") end local locale = string.gsub(zs.params(1),"%s+","%%20") local page = http.request("http://www.wunderground.com/cgi-bin/findweather/getForecast?query=" .. locale .. "&wuSelect=WEATHER") local location = string.match(page,'title="([%w%s,]+) RSS"') --print("Gathering weather information for " .. location .. ".") --local windspeed = string.match(page,'<span class="nobr"><span class="b">([%d.]+)</span>&nbsp;mph</span>') --print(windspeed) local condition = string.match(page, '<td class="vaM taC"><img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') --local image = string.match(page, '<img src="http://icons-ecast.wxug.com/i/c/a/(.+).gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') local temperature = string.match(page,'pwsvariable="tempf" english="&deg;F" metric="&deg;C" value="([%d.]+)">') local humidity = string.match(page,'pwsvariable="humidity" english="" metric="" value="(%d+)"') zs.say(location) --zs.say("image ./Images/" .. image .. ".gif") zs.say("<color limegreen>Condition:</color> <color white>" .. condition .. "</color>") zs.say("<color limegreen>Temperature: </color><color white>" .. temperature .. "F</color>") zs.say("<color limegreen>Humidity: </color><color white>" .. humidity .. "%</color>") My main issue is this: I changed the 'condition' and added the 'image' variables to what they are now. Even though the line it's supposed to be matching comes directly from the webpage, it fails to match at all. So I'm wondering what it is I'm missing that's preventing this code from working. If I take out the <td class="vaM taC">< img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" it'll match condition flawlessly. (For whatever reason, I can't get the above line to display correctly, but there is no space between the `< and img) Can anyone point out what is wrong with it? Aside from the pattern matching, I assure you the line is verbatim from the webpage. Another question I had is the ability to match across line breaks. Is there any possible way to do this? The reason why I ask is because on that same page, a few of the things I need to match are broken up on separate lines, and since the actual pattern I'm wanting to match shows up in other places on the page, I need to be able to match across line breaks to get the exact pattern. I appreciate any help in this matter!

    Read the article

  • The Endeca UI Design Pattern Library Returns

    - by Joe Lamantia
    I'm happy to announce that the Endeca UI Design Pattern Library - now titled the Endeca Discovery Pattern Library - is once again providing guidance and good practices on the design of discovery experiences.  Launched publicly in 2010 following several years of internal development and usage, the Endeca Pattern Library is a unique and valued source of industry-leading perspective on discovery - something I've come to appreciate directly through  fielding the consistent stream of inquiries about the library's status, and requests for its rapid return to public availability. Restoring the library as a public resource is only the first step!  For the next stage of the library's evolution, we plan to increase the scope of the guidance it offers beyond user interface design to the broader topic of discovery.  This could include patterns for architecture at the systems, user experience, and business levels; information and process models; analytical method and activity patterns for conducting discovery; and organizational and resource patterns for provisioning discovery capability in different settings.  We'd like guidance from the community on the kinds of patterns that are most valuable - so make sure to let us know. And we're also considering ways to increase the number of patterns the library offers, possibly by expanding the set of contributors and the authoring mechanisms. If you'd like to contribute, please get in touch. Here's the new address of the library: http://www.oracle.com/goto/EndecaDiscoveryPatterns And I should say 'Many thanks' to the UXDirect team and all the others within the Oracle family who helped - literally - keep the library alive, and restore it as a public resource.

    Read the article

  • Fetching Strategy example in repository pattern with pure POCO Entity framework

    - by Shawn Mclean
    I'm trying to roll out a strategy pattern with entity framework and the repository pattern using a simple example such as User and Post in which a user has many posts. From this answer here, I have the following domain: public interface IUser { public Guid UserId { get; set; } public string UserName { get; set; } public IEnumerable<Post> Posts { get; set; } } Add interfaces to support the roles in which you will use the user. public interface IAddPostsToUser : IUser { public void AddPost(Post post); } Now my repository looks like this: public interface IUserRepository { User Get<TRole>(Guid userId) where TRole : IUser; } Strategy (Where I'm stuck). What do I do with this code? Can I have an example of how to implement this, where do I put this? public interface IFetchingStrategy<TRole> { TRole Fetch(Guid id, IRepository<TRole> role) } My basic problem was what was asked in this question. I'd like to be able to get Users without posts and users with posts using the strategy pattern.

    Read the article

  • Psuedo-Backwards Builder Pattern?

    - by Avid Aardvark
    In a legacy codebase I have a very large class with far too many fields/responsibilities. Imagine this is a Pizza object. It has highly granular fields like: hasPepperoni hasSausage hasBellPeppers I know that when these three fields are true, we have a Supreme pizza. However, this class is not open for extension or change, so I can't add a PizzaType, or isSupreme(), etc. Folks throughout the codebase duplicate the same "if(a && b && c) then isSupreme)" logic all over place. This issue comes up for quite a few concepts, so I'm looking for a way to deconstruct this object into many subobjects, e.g. a pseudo-backwards Builder Pattern. PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME Dough dough = PizzaUnbuilder.buildDough(Pizza); Is this the right approach? Is there a pattern for this already? Thanks!

    Read the article

  • SSIS Design Pattern: Producing a Footer Row

    - by andyleonard
    The following is an excerpt from SSIS Design Patterns (now available in the UK!) Chapter 7, Flat File Source Patterns. The only planned appearance of all five authors presenting on SSIS Design Patterns is the SSIS Design Patterns day-long pre-conference session at the PASS Summit 2012 . Register today . Let’s look at producing a footer row and adding it to the data file. For this pattern, we will leverage project and package parameters. We will also leverage the Parent-Child pattern, which will be...(read more)

    Read the article

  • Java Inter Application Form Communication Observer Pattern

    - by ikurtz
    Observer pattern? Where do i get examples of this in Java (i know google but was hoping for some personal insight also.) On to a proper explanation of my issue: i have 3 forms/windows. "board" is the main form that loads as the application. "chat" is where the text chat takes place. "network" is where network connection is established. i have the game (connect4) working locally and i would like to implement a networked version of it also. my idea is maybe it is related to Observer pattern to have a thread (or something) monitoring network state during runtime and update the chat and board forms of the current network status as well as delivering received data from the network. are my ideas valid? or how should i go about establishing network and network status updates throughout the application? thank you for your input.

    Read the article

  • rails arguments to after_save observer

    - by ash34
    Hi, I want users to enter a comma-delimited list of logins on the form, to be notified by email when a new comment/post is created. I don't want to store this list in the database so I would use a form_tag_helper 'text_area_tag' instead of a form helper text_field. I have an 'after_save' observer which should send an email when the comment/post is created. As far as I am aware, the after_save event only takes the model object as the argument, so how do I pass this non model backed list of logins to the observer to be passed on to the Mailer method that uses them in the cc list. thanks

    Read the article

  • How to handle data output in an Observer?

    - by Mannaz
    I have an Observable and an Observer. The observable does download some stuff in a background thread and calls notifyObservers to let the observers read the status. At some point in public void update the observer tries to updates the GUI ((TextView)findViewById('R.id.foo')).setText("bar"); but it seems like the observable thread calls this method, because the Observable (!!!) throws this: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRoot.checkThread(ViewRoot.java:2462) at android.view.ViewRoot.requestLayout(ViewRoot.java:512) ... at com.mynamespace.acitivty.TrackActivity.startPlay(TrackActivity.java:72) at com.mynamespace.acitivty.TrackActivity.update(TrackActivity.java:107) at java.util.Observable.notifyObservers(Observable.java:147) at java.util.Observable.notifyObservers(Observable.java:128) at com.mynamespace.module.communication.Download.stateChanged(Download.java:213) at com.mynamespace.module.communication.Download.run(Download.java:186) at java.lang.Thread.run(Thread.java:1058) Is there some way I can prevent this from happening? I'm sure I'm missing something obvious here.

    Read the article

  • Rosetta Stone: Observer Pattern

    - by Shiftbit
    How is the Observer Pattern expressed in various programming languages? Can you provide a code snippet that illustrates the major differences in each language. This post is intended to demonstrate the differences of this commonly used design pattern. I will start this off with a Java example. Remember to start your answer off with the language being demonstrated.

    Read the article

  • Observer Design Pattern - multiple event types

    - by David
    I'm currently implementing the Observer design pattern and using it to handle adding items to the session, create error logs and write messages out to the user giving feedback on their actions (e.g. You've just logged out!). I began with a single method on the subject called addEvent() but as I added more Observers I found that the parameters required to detail all the information I needed for each listener began to grow. I now have 3 methods called addMessage(), addStorage() and addLog(). These add data into an events array that has a key related to the event type (e.g. log, message, storage) but I'm starting to feel that now the subject needs to know too much about the listeners that are attached. My alternative thought is to go back to addEvent() and pass an event type (e.g. USER_LOGOUT) along with the data associated and each Observer maintains it's own list of event handles it is looking for (possibly in a switch statement), but this feels cumbersome. Also, I'd need to check that sufficient data had also been passed along with the event type. What is the correct way of doing this? Please let me know if I can explain any parts of this further. I hope you can help and see the problem I'm battling with.

    Read the article

  • SSIS Design Pattern: Loading Variable-Length Rows

    - by andyleonard
    Introduction I encounter flat file sources with variable-length rows on occassion. Here, I supply one SSIS Design Pattern for loading them. What's a Variable-Length Row Flat File? Great question - let's start with a definition. A variable-length row flat file is a text source of some flavor - comma-separated values (CSV), tab-delimited file (TDF), or even fixed-length, positional-, or ordinal-based (where the location of the data on the row defines its field). The major difference between a "normal"...(read more)

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >