Search Results

Search found 2008 results on 81 pages for 'factory girl'.

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

  • Python: Class factory using user input as class names

    - by Sano98
    Hi everyone, I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str(myArcher.strength) Archer.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to the desired output: Strenght ofmyarcher: 5 Strenght ofmyarcher: 2 But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this: class Meta(type, subclassname): def __new__(cls, subclassname, bases, dct): return type.__new__(cls, subclassname, Unit, dct) factory = Meta() factory.__new__("Soldier") but no luck. I guess I haven't really understood what new does here. What I want as a result here is class Soldier(Unit): pass being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created. Any ideas? Many thanks in advance! Bye -Sano

    Read the article

  • Seam @Factory in abstract base class?

    - by Shadowman
    I've got a series of web actions I'm implementing in Seam to perform create, read, update, etc. operations. For my read/update/delete actions, I'd like to have individual action classes that all extend an abstract base class. I'd like to put the @Factory method in the abstract base class to retrieve the item that is to be acted upon. For example, I have this as the base class: public abstract class BaseAction { @In(required=false)@Out(required=false) private MyItem item=null; public MyItem getItem(){...} public void setItem(...){...} @Factory("item") public void initItem(){...} } My subclasses would extend BaseAction, so that I don't have to repeat the logic to load the item that is to be viewed, deleted, updated, etc. However, when I start my application, Seam throws errors saying I have declared multiple @Factory's for the same object. Is there any way around this? Is there any way to provide the @Factory in the base class without encoutnering these errors?

    Read the article

  • Complicated .NET factory design

    - by Tom W
    Hello SO; I'm planning to ask a fairly elaborate question that is also something of a musing here, so bear with me... I'm trying to design a factory implementation for a simulation application. The simulation will consist of different sorts of entities i.e. it is not a homogenous simulation in any respect. As a result, there will be numerous very different concrete implementations and only the very general properties will be abstracted at the top level. What I'd like to be able to do is create new simulation entities by calling a method on the model with a series of named arguments representing the parameters of the entity, and have the model infer what type of object is being described by the inbound parameters (from the names of the parameters and potentially the sequence they occur in) and call a factory method on the appropriate derived class. For example, if I pass the model a pair of parameters (Param1=5000, Param2="Bacon") I would like it to infer that the names Param1 and Param2 'belong' to the class "Blob1" and call a shared function "getBlob1" with named parameters Param1:=5000, Param2:="Bacon" whereas if I pass the model (Param1=5000, Param3=50) it would call a similar factory method for Blob2; because Param1 and Param3 in that order 'belong' to Blob2. I foresee several issues to resolve: Whether or not I can reflect on the available types with string parameter names and how to do this if it's possible Whether or not there's a neat way of doing the appropriate constructor inference from the combinatoric properties of the argument list or whether I'm going to have to bodge something to do it 'by hand'. If possible I'd like the model class to be able to accept parameters as parameters rather than as some collection of keys and values, which would require the model to expose a large number of parametrised methods at runtime without me having to code them explicitly - presumably one for every factory method available in the relevant namespace. What I'm really asking is how you'd go about implementing such a system, rather than whether or not it's fundamentally possible. I don't have the foresight or experience with .NET reflection to be able to figure out a way by myself. Hopefully this will prove an informative discussion.

    Read the article

  • How to name a static factory method in the utility class?

    - by leventov
    I have an interface MyLongNameInterface with a counterpart utility class MyLongNameInterfaces. What is the best name for a static factory method in the utility class, which creates an instance of MyLongNameInterface? MyLongNameInterfaces.newInstance() -- a new instance of the utility class? MyLongNameInterfaces.newMyLongNameInterface() -- too verbose MyLongNameInterfaces.create() -- create an instance of the utility class? Also, create is not a widely used conventional verb in Java better option?

    Read the article

  • Factory Method and Cyclic Dependancy

    - by metdos
    If I'm not wrong, because of its nature in factory method there is cyclic dependency: Base class needs to know subclasses because it creates them, and subclasses need to know base class. Having cyclic dependency is bad programming practice, is not it? Practically I implemented a factory, I have problem above, even I added #ifndef MYCLASS_H #define MYCLASS_H #endif I'm still getting Compiler Error C2504 'class' : base class undefined And this error disappers when I remove subclass include from base class header.

    Read the article

  • Factory(:user) hits database?

    - by davidegp
    Playing around with factories, which I read weren't supposed to hit the database, allowing you to avoid having your controller specs interacting with the DB. But when I fire up the Rails console in test and use a factory to create a sample user, I noticed an actual user gets created in the database. Huh? (Using Rails 2.3.8 and Factory Girl 1.2.3.)

    Read the article

  • Calling a Factory in AngularJS

    - by Kohjah Breese
    How do you call a factory? As defined below. angular.module('fb.services', []).factory('getQueryString', function () { return { call: function () { var result = {}, queryString = qs.substring(1), re = /([^&=]+)=([^&]*)/g, m; while (m = re.exec(queryString)) result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); return result; } } }); alert(getQueryString.call('this=that&me=you'));

    Read the article

  • Factory Pattern - when do you say you need a specialised factory

    - by dbones
    Hi, I am having a little design crisis, I am making a Plane class, which is made of an engine 2 wings and N seats The engine takes in a engine size, and the wings have a span. would this still be feasible to have a PlaneFactory, when the factory may have to take in multiple parameters to setup the plane (wings, engine, no of seats) thanks in advance bones

    Read the article

  • Does this factory method pattern example violate open-close?

    - by William
    In Head-First Design Patterns, they use a pizza shop example to demonstrate the factory method pattern. public abstract class PizzaStore { public Pizza orderPizza(String type) { Pizza pizza; pizza = createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } abstract Pizza createPizza(String type) } public class NYPizzaStore extends PizzaStore { Pizza createPizza(String item) { if (item.equals("cheese") { return new NYStyleCheesePizza(); } else if (item.equals("veggie")) { return new NYStyleVeggiePizza(); } else if (item.equals("clam")) { return new NYStyleClamPizza(); } else if (item.equals("pepperoni")) { return new NYStylePepperioniPizza(); } else return null; } } I don't understand how this pattern is not violating open-close. What if we require a beef Pizza, then we must edit the if statement in the NYPizzaStore class.

    Read the article

  • Can the Singleton be replaced by Factory?

    - by lostiniceland
    Hello Everyone There are already quite some posts about the Singleton-Pattern around, but I would like to start another one on this topic since I would like to know if the Factory-Pattern would be the right approach to remove this "anti-pattern". In the past I used the singleton quite a lot, also did my fellow collegues since it is so easy to use. For example, the Eclipse IDE or better its workbench-model makes heavy usage of singletons as well. It was due to some posts about E4 (the next big Eclipse version) that made me start to rethink the singleton. The bottom line was that due to this singletons the dependecies in Eclipse 3.x are tightly coupled. Lets assume I want to get rid of all singletons completely and instead use factories. My thoughts were as follows: hide complexity less coupling I have control over how many instances are created (just store the reference I a private field of the factory) mock the factory for testing (with Dependency Injection) when it is behind an interface In some cases the factories can make more than one singleton obsolete (depending on business logic/component composition) Does this make sense? If not, please give good reasons for why you think so. An alternative solution is also appreciated. Thanks Marc

    Read the article

  • I'm using a sequence in Factory Girl to get unique values but I'm getting validation errors

    - by Sean Seefried
    I have a model defined this way class Lga < ActiveRecord::Base validates_uniqueness_of :code validates_presence_of :name end I've defined a factory for Lgas with Factory.sequence(:lga_id) { |n| n + 10000 } Factory.define :lga do |l| id = Factory.next :lga_id l.code "lga_#{id}" l.name "LGA #{id}" end However, when I run Factory.create(:lga) Factory.create(:lga) in script/console I get >> Factory.create(:lga) => #<Lga id: 2, code: "lga_10001", name: "LGA 10001", created_at: "2010-03-18 23:55:29", updated_at: "2010-03-18 23:55:29"> >> Factory.create(:lga) ActiveRecord::RecordInvalid: Validation failed: Code has already been taken

    Read the article

  • Factory Method pattern and public constructor

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

    Read the article

  • Better to use constructor or method factory pattern?

    - by devoured elysium
    I have a wrapper class for the Bitmap .NET class called BitmapZone. Assuming we have a WIDTH x HEIGHT bitmap picture, this wrapper class should serve the purpose of allowing me to send to other methods/classes itself instead of the original bitmap. I can then better control what the user is or not allowed to do with the picture (and I don't have to copy the bitmap lots of times to send for each method/class). My question is: knowing that all BitmapZone's are created from a Bitmap, what do you find preferrable? Constructor syntax: something like BitmapZone bitmapZone = new BitmapZone(originalBitmap, x, y, width, height); Factory Method Pattern: BitmapZone bitmapZone = BitmapZone.From(originalBitmap, x , y, width, height); Factory Method Pattern: BitmapZone bitmapZone = BitmapZone.FromBitmap(originalBitmap, x, y, width, height); Other? Why? Thanks

    Read the article

  • C#/ASP.NET MVC 4 Instantiate Object Derived From Interface In Factory Method

    - by Chris
    Currently have a Factory class that features a GetSelector function, which returns a concrete implementation of ISelector. I have several different classes that implement ISelector and based on a setting I would like to receive the appropriate ISelector back. public interface ISelector { string GetValue(string Params); } public class XmlSelector : ISelector { public string GetValue(string Params) { // open XML file and get value } } public static class SelectorFactory { public static ISelector GetSelector() { return new XmlSelector(); // Needs changing to look at settings } } My question is what is the best way to store the setting? I am aware of using AppSettings etc. but I'm not sure whether I want to have to store strings in the web.config and perform a switch on it - just seems to be really tightly coupled in that if a new implementation of ISelector is made, then the Factory would need to be changed. Is there any way of perhaps storing an assembly name and instantiating based on that? Thanks, Chris

    Read the article

  • Factory Method Using Is/As Operator

    - by Swim
    I have factory that looks something like the following snippet. Foo is a wrapper class for Bar and in most cases (but not all), there is a 1:1 mapping. As a rule, Bar cannot know anything about Foo, yet Foo takes an instance of Bar. Is there a better/cleaner approach to doing this? public Foo Make( Bar obj ) { if( obj is Bar1 ) return new Foo1( obj as Bar1 ); if( obj is Bar2 ) return new Foo2( obj as Bar2 ); if( obj is Bar3 ) return new Foo3( obj as Bar3 ); if( obj is Bar4 ) return new Foo3( obj as Bar4 ); // same wrapper as Bar3 throw new ArgumentException(); } At first glance, this question might look like a duplicate (maybe it is), but I haven't seen one exactly like it. Here is one that is close, but not quite: http://stackoverflow.com/questions/242097/factory-based-on-typeof-or-is-a

    Read the article

  • Changing the connection factory JNDI dynamically in Ftp Adapter

    - by [email protected]
    Consider a usecase where you need to send the same file over to five different ftp servers. The first thought that might come to mind is to create five FtpAdapter references one for each connection-factory location. However, this is not the most optimal approach and this is exactly where "Dynamic Partner Links" come into play in 11g.    If you're running the adapter in managed mode, it would require you to configure the connection factory JNDI in the appserver console for the FtpAdapter. In the sample below, I have mapped the connection-factory JNDI location "eis/Ftp/FtpAdapter" with the ftp server running on localhost.           After you've configured the connection factory on your appserver, you will need to refer to the connection-factory JNDI in the jca artifact of your SCA process. In the example below, I've instructed the FTPOut reference to use the ftp server corresponding to "eis/Ftp/FtpAdapter".     The good news is that you can change this connection-factory location dynamically using jca header properties in both BPEL as well as Mediator service engines. In order to do so, the business scenario involving BPEL or Mediator would be required to use a reserved jca header property "jca.jndi" as shown below.     Similarly, for mediator, the mplan would look as shown below.       Things to remember while using dynamic partner links: 1) The connection factories must be pre-configured on the SOA server. In our BPEL example above, both "eis/Ftp/FtpAdater1" and "eis/Ftp/FtpAdater2" must be configured in the weblogic deployment descriptor for the FtpAdapter prior to deploying the scenario. 2) Dynamic Partner Links are applicable to outbound invocations only.    

    Read the article

  • (static initialization order?!) problems with factory pattern

    - by smerlin
    Why does following code raise an exception (in createObjects call to map::at) alternativly the code (and its output) can be viewed here intererestingly the code works as expected if the commented lines are uncommented with both microsoft and gcc compiler (see here), this even works with initMap as ordinary static variable instead of static getter. The only reason for this i can think of is that the order of initialization of the static registerHelper_ object (factory_helper_)and the std::map object (initMap) are wrong, however i cant see how that could happen, because the map object is constructed on first usage and thats in factory_helper_ constructor, so everything should be alright shouldnt it ? I am even more suprised that those doNothing() lines fix the issue, because that call to doNothing() would happen after the critical section (which currently fails) is passed anyway. EDIT: debugging showed, that without the call to factory_helper_.doNothing(), the constructor of factory_helper_ is never called. #include <iostream> #include <string> #include <map> #define FACTORY_CLASS(classtype) \ extern const char classtype##_name_[] = #classtype; \ class classtype : FactoryBase<classtype,classtype##_name_> namespace detail_ { class registerHelperBase { public: registerHelperBase(){} protected: static std::map<std::string, void * (*)(void)>& getInitMap() { static std::map<std::string, void * (*)(void)>* initMap = 0; if(!initMap) initMap= new std::map<std::string, void * (*)(void)>(); return *initMap; } }; template<class TParent, const char* ClassName> class registerHelper_ : registerHelperBase { static registerHelper_ help_; public: //void doNothing(){} registerHelper_(){ getInitMap()[std::string(ClassName)]=&TParent::factory_init_; } }; template<class TParent, const char* ClassName> registerHelper_<TParent,ClassName> registerHelper_<TParent,ClassName>::help_; } class Factory : detail_::registerHelperBase { private: Factory(); public: static void* createObject(const std::string& objclassname) { return getInitMap().at(objclassname)(); } }; template <class TClass, const char* ClassName> class FactoryBase { private: static detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> factory_helper_; static void* factory_init_(){ return new TClass();} public: friend class detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName>; FactoryBase(){ //factory_helper_.doNothing(); } virtual ~FactoryBase(){}; }; template <class TClass, const char* ClassName> detail_::registerHelper_<FactoryBase<TClass,ClassName>,ClassName> FactoryBase<TClass,ClassName>::factory_helper_; FACTORY_CLASS(Test) { public: Test(){} }; int main(int argc, char** argv) { try { Test* test = (Test*) Factory::createObject("Test"); } catch(const std::exception& ex) { std::cerr << "caught std::exception: "<< ex.what() << std::endl; } #ifdef _MSC_VER system("pause"); #endif return 0; }

    Read the article

  • Abstract Methods in "Product" - Factory Method C#

    - by Regina Foo
    I have a simple class library (COM+ service) written in C# to consume 5 web services: Add, Minus, Divide, Multiply and Compare. I've created the abstract product and abstract factory classes. The abstract product named WS's code: public abstract class WS { public abstract double Calculate(double a, double b); public abstract string Compare(double a, double b); } As you see, when one of the subclasses inherits WS, both methods must be overridden which might not be useful in some subclasses. E.g. Compare doesn't need Calculate() method. To instantiate a new CompareWS object, the client class will call the CreateWS() method which returns a WS object type. public class CompareWSFactory : WSFactory { public override WS CreateWS() { return new CompareWS(); } } But if Compare() is not defined as abstract in WS, the Compare() method cannot be invoked. This is only an example with two methods, but what if there are more methods? Is it stupid to define all the methods as abstract in the WS class? My question is: I want to define abstract methods that are common to all subclasses of WS whereas when the factory creates a WS object type, all the methods of the subclasses can be invoked (overridden methods of WS and also the methods in subclasses). How should I do this?

    Read the article

  • Generic factory of generic containers

    - by Feuermurmel
    I have a generic abstract class Factory<T> with a method createBoxedInstance() which returns instances of T created by implementations of createInstance() wrapped in the generic container Box<T>. abstract class Factory<T> { abstract T createInstance(); public final Box<T> createBoxedInstance() { return new Box<T>(createInstance()); } public final class Box<T> { public final T content; public Box(T content) { this.content = content; } } } At some points I need a container of type Box<S> where S is an ancestor of T. Is it possible to make createBoxedInstance() itself generic so that it will return instances of Box<S> where S is chosen by the caller? Sadly, defining the function as follows does not work as a type parameter cannot be declared using the super keyword, only used. public final <S super T> Box<S> createBoxedInstance() { return new Box<S>(createInstance()); } The only alternative I see, is to make all places that need an instance of Box<S> accept Box<? extends S> which makes the container's content member assignable to S. Is there some way around this without re-boxing the instances of T into containers of type Box<S>? (I know I could just cast the Box<T> to a Box<S> but I would feel very, very guilty.)

    Read the article

  • Solution Factory for Visual Studio 2010

    - by Mendy
    I love the idea behind Solution Factory project. But, unfortunately this project have a few bugs. Is anyone using it successfully with visual studio 2010? Is there any other better option for the same task? (of creating a new project based on existed one).

    Read the article

  • Simple factory to retrieve files using constructor dependency injection

    - by mrblah
    I want to create a class, that is flexible so I can switch implementations. Problem: Store files/documents Options: either store locally on the server filesystem, database or etc. Can someone help with a skeleton structure of the class, and how I would call it? I am not using an IoC, and don't really want to just yet. I just want the flexibility where I would make maybe 1 code change in the factory to call another implementation.

    Read the article

  • when to use the abstract factory pattern?

    - by hguser
    Hi: I want to know when we need to use the abstract factory pattern. Here is an example,I want to know if it is necessary. The UML THe above is the abstract factory pattern, it is recommended by my classmate. THe following is myown implemention. I do not think it is necessary to use the pattern. And the following is some core codes: package net; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class Test { public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { DaoRepository dr=new DaoRepository(); AbstractDao dao=dr.findDao("sql"); dao.insert(); } } class DaoRepository { Map<String, AbstractDao> daoMap=new HashMap<String, AbstractDao>(); public DaoRepository () throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { Properties p=new Properties(); p.load(DaoRepository.class.getResourceAsStream("Test.properties")); initDaos(p); } public void initDaos(Properties p) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String[] daoarray=p.getProperty("dao").split(","); for(String dao:daoarray) { AbstractDao ad=(AbstractDao)Class.forName(dao).newInstance(); daoMap.put(ad.getID(),ad); } } public AbstractDao findDao(String id) {return daoMap.get(id);} } abstract class AbstractDao { public abstract String getID(); public abstract void insert(); public abstract void update(); } class SqlDao extends AbstractDao { public SqlDao() {} public String getID() {return "sql";} public void insert() {System.out.println("sql insert");} public void update() {System.out.println("sql update");} } class AccessDao extends AbstractDao { public AccessDao() {} public String getID() {return "access";} public void insert() {System.out.println("access insert");} public void update() {System.out.println("access update");} } And the content of the Test.properties is just one line: dao=net.SqlDao,net.SqlDao So any ont can tell me if this suitation is necessary?

    Read the article

  • What exactly is a Class Factory?

    - by Olaseni
    I see the word thrown around often, and I may have used it myself in code and libraries over time, but I never really got it. In most write-ups I came across, they just went on expecting you to figure it out. What is a Class Factory? Can someone explain the concept?

    Read the article

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