Search Results

Search found 2051 results on 83 pages for 'abstract'.

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

  • Why should a class be anything other than "abstract" or "final/sealed"

    - by Nicolas Repiquet
    After 10+ years of java/c# programming, I find myself creating either: abstract classes: contract not meant to be instantiated as-is. final/sealed classes: implementation not meant to serve as base class to something else. I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming". Why should a class be anything other than "abstract" or "final/sealed" ? EDIT This great article explains my concerns far better than I can.

    Read the article

  • Difference between Factory Method and Abstract Factory design patterns using C#.Net

    - by nijhawan.saurabh
    First of all I'll just put both these patterns in context and describe their intent as in the GOF book: Factory Method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.   Abstract Factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.   Points to note:   Abstract factory pattern adds a layer of abstraction to the factory method pattern. The type of factory is not known to the client at compile time, this information is passed to the client at runtime (How it is passed is again dependent on the system, you may store this information in configuration files and the client can read it on execution). While implementing Abstract factory pattern, the factory classes can have multiple factory methods. In Abstract factory, a factory is capable of creating more than one type of product (Simpilar products are grouped together in a factory)   Sample implementation of factory method pattern   Let's see the class diagram first:                   ProductFactory.cs // ----------------------------------------------------------------------- // <copyright file="ProductFactory.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public abstract class ProductFactory     {         /// <summary>         /// </summary>         /// <returns>         /// </returns>         public abstract Product CreateProductInstance();     } }     ProductAFactory.cs // ----------------------------------------------------------------------- // <copyright file="ProductAFactory.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public class ProductAFactory:ProductFactory     {         public override Product CreateProductInstance()         {             return new ProductA();         }     } }         // ----------------------------------------------------------------------- // <copyright file="ProductBFactory.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public class ProductBFactory:ProductFactory     {         public override Product CreateProductInstance()         {             return new ProductB();           }     } }     // ----------------------------------------------------------------------- // <copyright file="Product.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public abstract class Product     {         public abstract string Name { get; set; }     } }     // ----------------------------------------------------------------------- // <copyright file="ProductA.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public class ProductA:Product     {         public ProductA()         {               Name = "ProductA";         }           public override string Name { get; set; }     } }       // ----------------------------------------------------------------------- // <copyright file="ProductB.cs" company=""> // TODO: Update copyright text. // </copyright> // -----------------------------------------------------------------------   namespace FactoryMethod {     using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;       /// <summary>     /// TODO: Update summary.     /// </summary>     public class ProductB:Product     {          public ProductB()         {               Name = "ProductA";         }         public override string Name { get; set; }     } }     Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace FactoryMethod {     class Program     {         static void Main(string[] args)         {             ProductFactory pf = new ProductAFactory();               Product product = pf.CreateProductInstance();             Console.WriteLine(product.Name);         }     } }       Normal 0 false 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:10.0pt; mso-para-margin-left:0in; line-height:115%; 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;}

    Read the article

  • Desktop Fun: Abstract Icon Packs

    - by Asian Angel
    Do you prefer a more unique, artistic, or alternative look for your desktop setup? Then you will definitely want to have a look through our Abstract Icon Packs collection. Just set your imagination loose and enjoy the wonderful desktops that these icon packs can inspire for you. Note: To customize the icon setup on your Windows 7 & Vista systems see our article here. Using Windows XP? We have you covered here. Sneak Preview For this week’s preview desktop we created an Alien Desert Planet theme using the Abstract Symbol Icons pack shown below. Note: The original, unmodified version of this wallpaper can be found here. Here is a closer look at the icons we used for our new theme… The Icon Packs Match-stick-play Icons *.ico format only Download Abstract Symbol Icons *.ico format only Download Allomantic Metals *.ico format only Download Mutated Snowflake Icon Set *.ico format only Download Shades of Geometry *.ico format only Download Starry Objects Icons *.ico format only Download New Sin – Abstract Human Icons *.ico, .png, and .psd format Note: While most of the icons in this pack look similar at first glance, there are differences when viewed at a larger size. Download Mysterious Icons *.ico format only Download Alien Icons *.ico format only Download Beads Icons *.ico format only Download Magic Flowers Icons *.ico format only Download Circle Shapes Icons *.ico format only Download geometric doc icons *.png format only Download alumina *.png format only Download Citiscape dockicons *.png format only Download Wanting more great icon sets to look through? Be certain to visit our Desktop Fun section for more icon goodness! Latest Features How-To Geek ETC How to Use the Avira Rescue CD to Clean Your Infected PC The Complete List of iPad Tips, Tricks, and Tutorials Is Your Desktop Printer More Expensive Than Printing Services? 20 OS X Keyboard Shortcuts You Might Not Know HTG Explains: Which Linux File System Should You Choose? HTG Explains: Why Does Photo Paper Improve Print Quality? Add Falling Snow to Webpages with the Snowfall Extension for Opera [Browser Fun] Automatically Keep Up With the Latest Releases from Mozilla Labs in Firefox 4.0 A Look Back at 2010 Through Infographics Monitor the Weather with the Weather Forecast Extension for Opera Orbiting at the Edge of the Atmosphere Wallpaper Simon’s Cat Explores the Christmas Tree! [Video]

    Read the article

  • How can I implement an abstract singleton class in Java?

    - by Simon
    Here is my sample abstract singleton class: public abstract class A { protected static A instance; public static A getInstance() { return instance; } //...rest of my abstract methods... } And here is the concrete implementation: public class B extends A { private B() { } static { instance = new B(); } //...implementations of my abstract methods... } Unfortunately I can't get the static code in class B to execute, so the instance variable never gets set. I have tried this: Class c = B.class; A.getInstance() - returns null; and this ClassLoader.getSystemClassLoader().loadClass("B"); A.getInstance() - return null; Running both these in the eclipse debugger the static code never gets executed. The only way I could find to get the static code executed is to change the accessibility on B's constructor to public, and to call it. I'm using sun-java6-jre on Ubuntu 32bit to run these tests.

    Read the article

  • How can I create object in abstract class without having knowledge of implementation?

    - by Greg
    Hi, Is there a way to implement the "CreateNode" method in my library abstract below? Or can this only be done in client code outside the library? I current get the error "Cannot create an instance of the abstract class or interface 'ToplogyLibrary.AbstractNode" public abstract class AbstractTopology<T> { // Properties public Dictionary<T, AbstractNode<T>> Nodes { get; private set; } public List<AbstractRelationship<T>> Relationships { get; private set; } // Constructors protected AbstractTopology() { Nodes = new Dictionary<T, AbstractNode<T>>(); } // Methods public AbstractNode<T> CreateNode() { var node = new AbstractNode<T>(); // ** Does not work ** Nodes.Add(node.Key, node); } } } public abstract class AbstractNode<T> { public T Key { get; set; } } public abstract class AbstractRelationship<T> { public AbstractNode<T> Parent { get; set; } public AbstractNode<T> Child { get; set; } }

    Read the article

  • Best method of including an abstract in a latex 'book'?

    - by olan
    Hello there. I've been looking for the answer to this question for a while now but can't seem to find it, so I'm hoping someone on here can help me. I'm writing up a thesis in Latex, and really like the \frontmatter, \mainmatter and \backmatter ability when using the "book" environment. However I need to add an abstract and the \begin{abstract} environment is undefined when creating a "book". If I change to a "report" however, I lose the functionality of the *matter terms. So what I really need to know is: is there a simple method of including an abstract in a "book" and have it formatted the same as it would be in a "report"? (i.e. centered vertically and horizontally with an 'abstract' heading) Thanks for any help! First post on stackoverflow after reading for months!

    Read the article

  • Can You Have "Empty" Abstract/Classes?

    - by ShrimpCrackers
    Of course you can, I'm just wondering if it's rational to design in such a way. I'm making a breakout clone and was doing some class design. I wanted to use inheritance, even though I don't have to, to apply what I've learned in C++. I was thinking about class design and came up with something like this: GameObject - base class (consists of data members like x and y offsets, and a vector of SDL_Surface* MovableObject : GameObject - abstract class + derived class of GameObject (one method void move() = 0; ) NonMovableObject : GameObject - empty class...no methods or data members other than constructor and destructor(at least for now?). Later I was planning to derive a class from NonMovableObject, like Tileset : NonMovableObject. I was just wondering if "empty" abstract classes or just empty classes are often used...I notice that the way I'm doing this, I'm just creating the class NonMovableObject just for sake of categorization. I know I'm overthinking things just to make a breakout clone, but my focus is less on the game and more on using inheritance and designing some sort of game framework.

    Read the article

  • Generate Unique Abstract Backgrounds with Ablaze

    - by Jason Fitzpatrick
    If you want custom and unique backgrounds without having to code your own image-generating engine, Ablaze makes it simple (and fun) to create abstract images. You can customize a wide array of options in Ablaze including the base shape (ring, horizontal line, or random), number of particles, distance each particle travels, and the speed (if you increase the speed range you get more distinct lines and if you decrease it you get smoother smokier shapes). You can also seed the design with a color palette pulled from any image you provide (the sample above was seeded with a Wonder Woman comic panel). Tweak and reset the pattern generation as much as you want; when you create an abstract image worthy of your desktop just click the save button to grab a copy of it in PNG format. Ablaze [via Flowing Data] How To Create a Customized Windows 7 Installation Disc With Integrated Updates How to Get Pro Features in Windows Home Versions with Third Party Tools HTG Explains: Is ReadyBoost Worth Using?

    Read the article

  • Can i override an abstract method written in a parent class, with a different name in a child class?

    - by Ranhiru
    abstract class SettingSaver { public abstract void add(string Name, string Value); public abstract void remove(string SettingName); } class XMLSettings : SettingSaver { public override void add(string Name, string Value) { throw new NotImplementedException(); } public override void remove(string SettingName) { throw new NotImplementedException(); } } Is there anyway that I can change the name of the add function in XMLSettings class to addSetting but make sure it overrides the add function in the SettingSaver? I know it should be definitely overridden in derived classes but just want to know whether I can use a different name :) Thanx in advance :D

    Read the article

  • Building a database class in PHP

    - by Sprottenwels
    I wonder if I should write a database class for my application, and if so, how to accomplish it? Over there on SO, a guy mentioned it should be written as an abstract class. However, I can't understand why this would be a benefit. Do I understand correctly, that if I would write an abstract class, every other class that methods will need a database connection, could simply extend this abstract class and have it's own database object? If so, how is this different from a "normal" class where I could instantiate an database object? Another method would be to completely forget about my own class and to instantiate a mysqli object on demand. What do you recommend?

    Read the article

  • What is the better design decision approach?

    - by palm snow
    I have two classes (MyFoo1 and MyFoo2) that share some common functionality. So far it does not seem like I need any polymorphic inheritence but at this point I am considering the following options: Have the common functionality in a utility class. Both of these classes call these methods from that utility class. Have an abstract class and implement common methods in that abstract class. Then derive MyFoo1 and MyFoo2 from that abstract class. Any suggestion on what would be a better design decision?

    Read the article

  • Extending abstract classes in c#

    - by ng
    I am a Java developer and I have noticed some differences in extending abstract classes in c# as opposed to Java. I was wondering how a c# developer would achived the following. 1) Covarience public abstract class A { public abstract List<B> List(); } public class BList : List<T> where T : B { } public abstract class C : A { public abstract BList List(); } So in the above hierarchy, there is covarience in C where it returns a type compatible with what A returns. However this gives me an error in Visual Studio. Is there a way to specify a covarient return type in c#? 2) Adding a setter to a property public abstract class A { public abstract String Name { get; } } public abstract class B : A { public abstract String Name { get; set } } Here the compiler complains of hiding. Any suggestions? Please do not suggest using interfaces unless that is the ONLY way to do this.

    Read the article

  • How to avoid general names for abstract classes?

    - by djechlin
    In general it's good to avoid words like "handle" or "process" as part of routine names and class names, unless you are dealing with (e.g.) file handles or (e.g.) unix processes. However abstract classes often don't really know what they're going to do with something besides, say, process it. In my current situation I have an "EmailProcessor" that logs into a user's inbox and processes messages from it. It's not really clear to me how to give this a more precise name, although I've noticed the following style matter arises: better to treat derived classes as clients and named the base class by the part of the functionality it implements? Gives it more meaning but will violate is-a. E.g. EmailAcquirer would be a reasonable name since it's acquiring for the derived class, but the derived class won't be acquiring for anyone. Or just really vague name since who knows what the derived classes will do. However "Processor" is still too general since it's doing many relevant operations, like logging in and using IMAP. Any way out of this dilemma? Problem is more evident for abstract methods, in which you can't really answer the question "what does this do?" because the answer is simply "whatever the client wants."

    Read the article

  • Getting link to abstract indexed in Google Scholar

    - by JordanReiter
    We have a large digital library with thousands of papers indexed in Google Scholar. We allow Google Scholar to index our PDFs but they're blocked unless you have a subscription. So Google has full-text indexing/searching of our PDFs (great!) but then the links point just to those PDFs (boo!) instead of the more helpful abstract pages. Does anyone know what could cause an issue like this? I am, to the best of my knowledge, following all of the guidelines laid out in their Inclusion Guidelines. Here's some example meta data: <meta name="citation_title" content="Sample Title"/> <meta name="citation_author" content="LastName, FirstName"/> <meta name="citation_publication_date" content="2012/06/26"/> <meta name="citation_volume" content="1"/> <meta name="citation_issue" content="1"/> <meta name="citation_firstpage" content="10"/> <meta name="citation_lastpage" content="20"/> <meta name="citation_conference_title" content="Name of the Conference"/> <meta name="citation_isbn" content="1-234567-89-X"/> <meta name="citation_pdf_url" content="http://www.example.org/p/1234/proceeding_1234.pdf"/> <meta name="citation_fulltext_html_url" content="http://www.example.org/f/1234/"/> <meta name="citation_abstract_html_url" content="http://www.example.org/p/1234/"/> <link rel="canonical" href="http://www.example.org/p/1234/" /> example.org/p/1234 is the abstract page for the article; example.org/f/1234 is the fulltext link accessible to subscribers only (and to Google Scholar). example.org/p/1234/proceeding_1234.pdf is the fulltext PDF link.

    Read the article

  • What am I not getting about this abstract class implementation?

    - by Schnapple
    PREFACE: I'm relatively inexperienced in C++ so this very well could be a Day 1 n00b question. I'm working on something whose long term goal is to be portable across multiple operating systems. I have the following files: Utilities.h #include <string> class Utilities { public: Utilities() { }; virtual ~Utilities() { }; virtual std::string ParseString(std::string const& RawString) = 0; }; UtilitiesWin.h (for the Windows class/implementation) #include <string> #include "Utilities.h" class UtilitiesWin : public Utilities { public: UtilitiesWin() { }; virtual ~UtilitiesWin() { }; virtual std::string ParseString(std::string const& RawString); }; UtilitiesWin.cpp #include <string> #include "UtilitiesWin.h" std::string UtilitiesWin::ParseString(std::string const& RawString) { // Magic happens here! // I'll put in a line of code to make it seem valid return ""; } So then elsewhere in my code I have this #include <string> #include "Utilities.h" void SomeProgram::SomeMethod() { Utilities *u = new Utilities(); StringData = u->ParseString(StringData); // StringData defined elsewhere } The compiler (Visual Studio 2008) is dying on the instance declaration c:\somepath\somecode.cpp(3) : error C2259: 'Utilities' : cannot instantiate abstract class due to following members: 'std::string Utilities::ParseString(const std::string &)' : is abstract c:\somepath\utilities.h(9) : see declaration of 'Utilities::ParseString' So in this case what I'm wanting to do is use the abstract class (Utilities) like an interface and have it know to go to the implemented version (UtilitiesWin). Obviously I'm doing something wrong but I'm not sure what. It occurs to me as I'm writing this that there's probably a crucial connection between the UtilitiesWin implementation of the Utilities abstract class that I've missed, but I'm not sure where. I mean, the following works #include <string> #include "UtilitiesWin.h" void SomeProgram::SomeMethod() { Utilities *u = new UtilitiesWin(); StringData = u->ParseString(StringData); // StringData defined elsewhere } but it means I'd have to conditionally go through the different versions later (i.e., UtilitiesMac(), UtilitiesLinux(), etc.) What have I missed here?

    Read the article

  • Can I use an abstract class instead of a private __construct() when creating a singleton in PHP?

    - by Pheter
    When creating a Singleton in PHP, I ensure that it cannot be instantiated by doing the following: class Singleton { private function __construct() {} private function __clone() {} public static function getInstance() {} } However, I realised that defining a class as 'abstract' means that it cannot be instantiated. So is there anything wrong with doing the following instead: abstract class Singleton { public static function getInstance() {} } The second scenario allows me to write fewer lines of code which would be nice. (Not that it actually makes much of a difference.)

    Read the article

  • Is it possible for an abstract class to force it's children to have a constructor in PHP?

    - by Logan Serman
    I would like to do something like this: abstract class Foo { public function __construct() { echo 'This is the parent constructor'; } abstract function __construct(); } class Bar extends Foo { // constructor is required as this class extends Foo public function __construct() { //call parent::__construct() if necessary echo 'This is the child constructor'; } } But I get a fatal error when doing this: Fatal error: Cannot redeclare Foo::__construct() in Foo.php on line 8 Is there another way to ensure child classes have a constructor?

    Read the article

  • How to determine which inheriting class is using an abstract class' methods.

    - by Kin
    In my console application have an abstract Factory class "Listener" which contains code for listening and accepting connections, and spawning client classes. This class is inherited by two more classes (WorldListener, and MasterListener) that contain more protocol specific overrides and functions. I also have a helper class (ConsoleWrapper) which encapsulates and extends System.Console, containing methods for writing to console info on what is happening to instances of the WorldListener and MasterListener. I need a way to determine in the abstract ListenerClass which Inheriting class is calling its methods. Any help with this problem would be greatly appreciated! I am stumped :X Simplified example of what I am trying to do. abstract class Listener { public void DoSomething() { if(inheriting class == WorldListener) ConsoleWrapper.WorldWrite("Did something!"); if(inheriting class == MasterListener) ConsoleWrapper.MasterWrite("Did something!"); } } public static ConsoleWrapper { public void WorldWrite(string input) { System.Console.WriteLine("[World] {0}", input); } } public class WorldListener : Listener { public void DoSomethingSpecific() { ConsoleWrapper.WorldWrite("I did something specific!"); } } public void Main() { new WorldListener(); new MasterListener(); } Expected output [World] Did something! [World] I did something specific! [Master] Did something! [World] I did something specific!

    Read the article

  • How to determine which inheriting class is using an abstract class's methods.

    - by Kin
    In my console application have an abstract Factory class "Listener" which contains code for listening and accepting connections, and spawning client classes. This class is inherited by two more classes (WorldListener, and MasterListener) that contain more protocol specific overrides and functions. I also have a helper class (ConsoleWrapper) which encapsulates and extends System.Console, containing methods for writing to console info on what is happening to instances of the WorldListener and MasterListener. I need a way to determine in the abstract ListenerClass which Inheriting class is calling its methods. Any help with this problem would be greatly appreciated! I am stumped :X Simplified example of what I am trying to do. abstract class Listener { public void DoSomething() { if(inheriting class == WorldListener) ConsoleWrapper.WorldWrite("Did something!"); if(inheriting class == MasterListener) ConsoleWrapper.MasterWrite("Did something!"); } } public static ConsoleWrapper { public void WorldWrite(string input) { System.Console.WriteLine("[World] {0}", input); } } public class WorldListener : Listener { public void DoSomethingSpecific() { ConsoleWrapper.WorldWrite("I did something specific!"); } } public void Main() { new WorldListener(); new MasterListener(); } Expected output [World] Did something! [World] I did something specific! [Master] Did something! [World] I did something specific!

    Read the article

  • Is there a case for parameterising using Abstract classes rather than Interfaces?

    - by Chris
    I'm currently developing a component based API that is heavily stateful. The top level components implement around a dozen interfaces each. The stock top-level components therefore sit ontop of a stack of Abstract implementations which in turn contain multiple mixin implementations and implement multiple mixin interfaces. So far, so good (I hope). The problem is that the base functionality is extremely complex to implement (1,000s of lines in 5 layers of base classes) and therefore I do not wish for component writers to implement the interfaces themselves but rather to extend my base classes (where all the boiler plate code is already written). If the API therefore accepts interfaces rather than references to the Abstract implementation that I wish for component writers to extends, then I have a risk that the implementer will not perform the validation that is both required and assumed by other areas of code. Therefore, my question is, is it sometimes valid to paramerise API methods using an abstract implementation reference rather than a reference to the interface(s) that it implements? Do you have an example of a well-designed API that uses this technique or am I trying to talk myself into bad-practice?

    Read the article

  • Which of these design patterns is superior?

    - by durron597
    I find I tend to design class structures where several subclasses have nearly identical functionality, but one piece of it is different. So I write nearly all the code in the abstract class, and then create several subclasses to do the one different thing. Does this pattern have a name? Is this the best way for this sort of scenario? Option 1: public interface TaxCalc { String calcTaxes(); } public abstract class AbstractTaxCalc implements TaxCalc { // most constructors and fields are here public double calcTaxes(UserFinancials data) { // code double diffNumber = getNumber(data); // more code } abstract protected double getNumber(UserFinancials data); protected double initialTaxes(double grossIncome) { // code return initialNumber; } } public class SimpleTaxCalc extends AbstractCalc { protected double getNumber(UserFinancials data) { double temp = intialCalc(data.getGrossIncome()); // do other stuff return temp; } } public class FancyTaxCalc extends AbstractTaxCalc { protected double getNumber(UserFinancials data) { int temp = initialCalc(data.getGrossIncome()); // Do fancier math return temp; } } Option 2: This version is more like the Strategy pattern, and should be able to do essentially the same sorts of tasks. public class TaxCalcImpl implements TaxCalc { private final TaxMath worker; public DummyImpl(TaxMath worker) { this.worker = worker; } public double calcTaxes(UserFinancials data) { // code double analyzedDouble = initialNumber; int diffNumber = worker.getNumber(data, initialNumber); // more code } protected int initialTaxes(double grossIncome) { // code return initialNumber; } } public interface TaxMath { double getNumber(UserFinancials data, double initial); } Then I could do: TaxCalc dum = new TaxCalcImpl(new TaxMath() { @Override public double getNumber(UserFinancials data, double initial) { double temp = data.getGrossIncome(); // do math return temp; }); And I could make specific implementations of TaxMath for things I use a lot, or I could make a stateless singleton for certain kinds of workers I use a lot. So the question I'm asking is: Which of these patterns is superior, when, and why? Or, alternately, is there an even better third option?

    Read the article

  • How can I make an "abstract" enum in a .NET class library?

    - by Lazlo
    I'm making a server library in which the packet association is done by enum. public enum ServerOperationCode : byte { LoginResponse = 0x00, SelectionResponse = 0x01, BlahBlahResponse = 0x02 } public enum ClientOperationCode : byte { LoginRequest = 0x00, SelectionRequest = 0x01, BlahBlahRequest = 0x02 } That works fine when you're working in your own project - you can compare which enum member is returned (i.e. if (packet.OperationCode == ClientOperationCode.LoginRequest)). However, since this is a class library, the user will have to define its own enum. Therefore, I have two enums to add as "abstract" - ServerOperationCode and ClientOperationCode. I know it's not possible to implement abstract enums in C#. How would I go doing this?

    Read the article

  • How do I ensure my abstract class's function can only operate on extenders of the same type as the c

    - by incrediman
    For example, let's say this is my abstract class: abstract class A{ int x; int y; void foo(A fooMe); } ...and B and C are two classes which extend A. What I want is for B to only be able to call foo() on other Bs, and for C to only be able to call foo() on other Cs. But I want this to be out of the hands of the programmer who's extending my A class - that is, I want a way to ensure this functionality within As code alone. What can I do? (If possible) I'd like to avoid any hack or generics solution that's too messy - I still want foo to be able to be called like this, for example: B b=new B(); B bb=new B(); bb.foo(b);

    Read the article

  • Using Lazy<T> and abstract wrapper class to lazy-load complex system parameters

    - by DigiMortal
    .NET Framework 4.0 introduced new class called Lazy<T> and I wrote blog post about it: .Net Framework 4.0: Using System.Lazy<T>. One thing is annoying for me – we have to keep lazy loaded value and its value loader as separate things. In this posting I will introduce you my Lazy<T> wrapper for complex to get system parameters that uses template method to keep lazy value loader in parameter class. Problem with original implementation Here’s the sample code that shows you how Lazy<T> is usually used. This is just sample code, don’t focus on the fact that this is dummy console application. class Program {     static void Main(string[] args)     {         var temperature = new Lazy<int>(LoadMinimalTemperature);           Console.WriteLine("Minimal room temperature: " + temperature.Value);         Console.ReadLine();     }       protected static int LoadMinimalTemperature()     {         var returnValue = 0;           // Do complex stuff here           return true;     } } The problem is that our class with many lazy loaded properties will grow messy if it has all value loading code inside it. This code may be complex for more than one parameter and in this case it is better to use separate class for this parameter. Defining base class for parameters As a first step I will define base class for all lazy-loaded parameters. This class is wrapper around Lazy<T> and it also offers one template method that parameter classes have to override to provide loaded data. public abstract class LazyParameter<T> {     private Lazy<T> _lazyParam;       public LazyParameter()     {         _lazyParam = new Lazy<T>(Load);     }       protected abstract T Load();       public T Value     {         get { return _lazyParam.Value; }     } } It is also possible to extend Lazy<T> but I don’t prefer to do it as Lazy<T> has six constructors we have to take care of. Also I don’t like to expose Lazy<T> public interface to users of my parameter classes. Creating parameter class Now it’s time to create our first parameter class. Notice how few stuff we have in this class besides overridden Load() method. public class MinimalRoomTemperature : LazyParameter<int> {     protected override int Load()     {         var returnValue = 0;           // Do complex stuff here           return returnValue;     } } Using parameter class is simple. Here’s my test code. class Program {     static void Main(string[] args)     {         var parameter = new MinimalRoomTemperature();         Console.WriteLine("Minimal room temperature: " + parameter.Value);         Console.ReadLine();     } } Conclusion Lazy<T> is useful class that you usually don’t want to use outside from API-s. I like this class but I don’t like when people are using this class directly in application code. In this posting I showed you how to use Lazy<T> with wrapper class to get complex parameter loading code out from classes that use this parameter. We ended up with generic base class for parameters that you can also use as base for other similar classes (you have to find better name to base class in this case).

    Read the article

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