Singletons and Inheritance

Hello all,
I want to write a set of classes in the following way. Say I have a class called Base from which SubX, SubY, and SubZ are derived. I would like Base to be a singleton class, with a getInstance() method, so that one and only one of the subclasses can ever be instantiated. Which particular subclass to instantiate is determined at run time.
// Create (or load or initialize...) subclass dynamically at run time (let's say SubY)
// From now on, I cannot instantiate any more classes derived from Base in this VM (i.e. no instances of SubX, SubY, or SubZ).
// Base.getInstance() now always returns the SubY singleton.
Anyone have ideas on how to do this?
Thanks in advance...
Matt

I think the main problem here is that to do this within the hierarchy is that it means a base class must have knowledge of its derrived classes. This is a pretty big OO no no (one reason for this is that it makes extending your hierarchy pretty difficult).
I think that what you want is a third party who manages your constraint (i.e, only one translator should be used, and should be available to everyone).
Ive got a couple of solutions - the first one would leave your translators not being singletons, the other one would.......
Solution one:
Have a singleton TranslatorFactory who provides you with a single translator:
Heres some classes/interfaces we need to know about:
public interface Translator
  // Your translation stuff:
  public void doTranslate();
public class ConcreteTranslatorA
  public ConcreteTranslatorA()
    // Allow construction....
  public void doTranslate()
    // Some Translation stuff
// The manager - exceptions dealt with in terms of Exception in this example just for clarity:
public class TranslatorFactory
  private TranslatorFactory mInstance;
  private Translator mTranslator;
  private static final String TRANSLATOR_PROPERTY="TRANSLATOR";
  public static TranslatorFactory GetInstance() throws Exception
    // usuall singleton stuff - create/provide instance
  public TranslatorFactory throws Exception
    // Create the translator here. You might do this by getting the class name from system properties, or by any other method you like  
   String aClassName=System.getProperty(TRANSLATOR_PROPERTY);
    mTranslator=(Translator)(Class.forName(aClassName).newInstance());
  public Translator getTranslator()
    return mTranslator;
}If you really want to prevent your translator instances being instantiated, you can do this another way:
1) Make their constructors private.
2) Make the TranslatorFactory a registry of Translators. Each translator uses a static initialiser to make itself known to the registry (in terms of a Translator). The registry caches each instance against its class name. The factory can then configure which translator to use based on some property. This is a good approach to take if the property can change: I.e, different translators can be provided at different times without incurring extra creation.
public class TranslatorRegistry
  private Map mTranslatorMap;
  public TranslatorRegistry GetInstance()
    // usual singleton stuff....
  public void register(Translator aTranslator)
    // cache the instance against its class name in the mTranslatorMap.
  public Translator getTranslator()
    // decide which translator to use from the cache, and supply it.
public class ConcreteRegisteringTranslatorA
  static
    // perform automatic registration:
    TranslatorRegsitry.GetInstance().register(new ConcreteRegisteringTranslatorA());
  protected ConcreteRegisteringTranslatorA
    // cant be constructed externally, but allow derrivation by keeping constructor protected
  public void doTranslation()
    // translation
}

Similar Messages

  • First Try with JE BDB - Indexes and Inheritance troubles... (FIXED)

    Hi Mark,
    Mark wrote:
    Hi, I'm a newbie here trying some stuff on JE BDB. And now I'm having
    I am happy to help you with this, but I'll have to ask you to re-post this question to the BDB JE forum, which is...
    Sorry for the mistake. I know now that here is the place to post my doubts.
    I'm really interested in JE BDB product. I think it is fantastic!
    Regarding my first post about "Indexes and Inheritance" on JE BDB, I found out the fix for that and actually, it wasn't about "Indexes and Inheritance" but "*Inheritance and Sequence*" because I have my "@Persistent public abstract class AbstractEntity" with a "@PrimaryKey(sequence = "ID_SEQ") private Long id" property.
    This class is extended by all my business classes (@Entity Employee and @Entity Department) so that my business classes have their PrimaryKey autoincremented by the sequence.
    But, all my business classes have the same Sequence Name: "ID_SEQ" then, when I start running my JE BDB at first time, I start saving 3 new Department objects and the sequence for these department objects star with "#1" and finishes with #3.
    Then I continue saving Employee objects (here was the problem) I thought that my next Sequence number could be #4 but actually it was #101 so when I tried to save my very first Employee, I set the property "managerId=null" since this employee is the Manager, then, when I tried to save my second Employee who is working under the first one (the manager employee), I got the following exception message:
    TryingJEBDBApp DatabaseExcaption: com.sleepycat.je.ForeignConstraintException: (JE 4.0.71) Secondary persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee#*managerId*
    foreign key not allowed: it is not present in the foreign database
    persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee
    The solution:
    I fixed it modifying the managerId value from "4" to "101" and it works now!
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...
    Have you any good material about these topics, perhaps a link where I can find more detailed information on these?
    Thanks in advance Mark, thanks for your attention on this and I will post more doubts in the future for sure ;0)
    Regards,
    Diego

    Hi Diego,
    I fixed it modifying the managerId value from "4" to "101" and it works now!I'm glad you found the problem. It is usually best to get the assigned ID from the entity object after you call put(), and then use that value to fill in related fields in other entities. The primary key field (assigned from the sequence) is set by the put() method.
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...Have you any good material about these topics, perhaps a link where I can find more detailed information on these? >
    To find documentation, start at the first message in the forum, the Welcome message:
    http://forums.oracle.com/forums/ann.jspa?annID=250
    This refers to the main JE doc page, the JE FAQ and a white paper on DPL queries. The FAQ has a section on the DPL, which refers to the javadoc. The DPL javadoc has lots of info on using cursors along with indexes (see EntityIndex, PrimaryIndex, SecondaryIndex). The white paper will be useful to you if you're accustomed to using SQL.
    I don't know of any doc on sequences other than the javadoc:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()
    This doc will point you to info on configuring the sequence, if that's what you're interested in.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • +, - button and inherited tick box is in disabled mode for account assignme

    In the attribute tab of org structure (PPOMA_BBP), we are not getting +, - button and inherited tick box is in disabled mode for account assignment category (attribute is KNT).
    We want to enter two values for the account assignment category with inherited tick box (ticked).
    Please suggest me how to get the +, - and inherited tick box (ticked) for the account assignment.
    Regards.

    Hi Imam,
    Unde attributes
    You will find one Application Toolbar...
    Overview, Select Attribute, Check Entries,Insert line,Delete line..
    So under All values you will find AcctAssigCat, Exculded, Default, Inheried
    Select the row and click on Insert Line, now you should be able to insert the new acct Assignment category
    rg
    sam

  • Generic and Inheritance, how to use them together?

    Hi guys, I am trynig to design some components, and they will use both Generics and Inheritance.
    Basically I have a class
    public class GModel <C>{
        protected C data;
        public C getData(){return data;}
    }//And its subclass
    public class ABCModel <C> extends GModel{
    }//On my guess, when I do
    ABCModel abcModel = new ABCModel<MyObject>();The data attribute should be from MyObject type, is it right?
    So, usign the netbeans when I do
    MyObject obj = abcModel.getData();I should not use any casting, since the generics would tell that return object from getDta would be the MyObject.
    Is this right? If yes; did someone try to do that on netbeans?
    Thanks and Regards

    public class GModel <C>{
    public class ABCModel <C> extends GModel{public class ABCModel <C> extends GModel<C>{
    ABCModel abcModel = new ABCModel<MyObject>();ABCModel<MyObject> abcModel = new ABCModel<MyObject>();

  • Singleton and non singleton in webdynpro java

    Hi All,
    where we use singleton and non singleton in webdynpro application.please send me with any example (scenario).
    Regards
    Anand

    Hello Anand,
    I think that your question is for u201CWeb Dynpro Javau201D forum..
    Please use the correct forum for your question.
    In general:: http://wiki.sdn.sap.com/wiki/display/WDJava/SingletonandNon-Singleton+Nodes
    There is example at : http://wiki.sdn.sap.com/wiki/display/WDJava/DynamicUIGeneration
    u201CWelcome to Web Dynpro Java! u201C  Wiki : http://wiki.sdn.sap.com/wiki/display/WDJava/WelcometoWebDynproJava%21
    Thank you and best regards, Natalia Khlopina

  • Exact difference betwteen aggregation and Inheritance with example

    hi everybody
    Just I got some doubt regarding the difference betwteen aggregation and Inheritance and where we can differntiate the use of each other. I am little bit confused with the two usages when refering to objects.
    Thank you

    ramsy wrote:
    hi everybody
    Just I got some doubt regarding the difference betwteen aggregation and Inheritance and where we can differntiate the use of each other. I am little bit confused with the two usages when refering to objects.
    Thank youIt's the difference between the "is-a" and "has-a" relationship. A Car is-a Vehicle. A Car has-a Engine.

  • When not using EJBs can I make BD a Singleton and cache facade instances?

    Hi,
    In an application which does not use EJBs can I make BD(Business Delegate) a singleton?
    I was very sure about doing this but when I tried Google on the same subject the answers were'nt supportive of this but that was in the context of applications which used EJBs. And also item 4 in Effective Java isnt very supportive of caching Objects at the drop of a hat.
    When not using EJBs would it be an unnecessary thing to make BD a singleton and cahce Facade instances in a BD and DAO instances in a Facade? I am planning to use a array based blocking bounded buffer for the purposes of caching. Or would it be better to make both BD and a facade as SIngletons and just cache DAOs in a Facade?
    Any suggestion would be of good help to me.
    Thanks a lot.

    Not sure I understand all your design, but you seem
    to describe an architecture where requests are queued
    and handled serially.Sorry if I messed up while explaining it. No, it will not be handled serially. Since the BD is a singleton multiple threads can pass messages to it simulteanously, a bit like an object of the Action class in Struts. Since I dont see having any synchronized methods in a BD requests will be handled simulteanously.
    The impact on throughput of handling requests
    serially (as opposed to parallelizing them) probably
    outweights by far the cost of instantiating one more
    object per request...Yes, I understand that but as I explained above the reqests wont be handled serially.
    To be more clear, I am thinking of using any one of these two things:
    1) BD(Singleton)-->Facade(Singleton, caches DAOs in a thread safe data structure)
    2)1) BD(Singleton, caches Facade instances in a thread safe data structure)-->Facade(caches DAOs in a thread safe data structure).
    the thread safe data structure I am planning to have is a array based bounded buffer which blocks using wait and notify mechanism.
    Thank you for the reply.

  • [svn] 2703: Fixes for bad links in seeTag and inheritance link.

    Revision: 2703
    Author: [email protected]
    Date: 2008-08-01 08:45:08 -0700 (Fri, 01 Aug 2008)
    Log Message:
    Fixes for bad links in seeTag and inheritance link.
    @seeTag was causing duplicate entries for package name in the array - which was causing a bad link..
    Bugs: SDK-9440, SDK-14265, SDK-12745
    QA: Yes
    Reviewed by: Paul
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-9440
    http://bugs.adobe.com/jira/browse/SDK-14265
    http://bugs.adobe.com/jira/browse/SDK-12745
    Modified Paths:
    flex/sdk/trunk/modules/compiler/asdoc/asDocHelper.as

    Revision: 2703
    Author: [email protected]
    Date: 2008-08-01 08:45:08 -0700 (Fri, 01 Aug 2008)
    Log Message:
    Fixes for bad links in seeTag and inheritance link.
    @seeTag was causing duplicate entries for package name in the array - which was causing a bad link..
    Bugs: SDK-9440, SDK-14265, SDK-12745
    QA: Yes
    Reviewed by: Paul
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-9440
    http://bugs.adobe.com/jira/browse/SDK-14265
    http://bugs.adobe.com/jira/browse/SDK-12745
    Modified Paths:
    flex/sdk/trunk/modules/compiler/asdoc/asDocHelper.as

  • Spatial index on table with object-column (and inheritance)

    Hi!
    Is it possible to create a spatial index on a table with an object-column (and inheritance) like this:
    CREATE OR REPLACE TYPE feature_type AS OBJECT (
    shape MDSYS.SDO_GEOMETRY
    ) NOT FINAL;
    CREATE OR REPLACE TYPE building_type UNDER feature_type (
    name VARCHAR2(50)
    CREATE TABLE features ( no NUMBER PRIMARY KEY, feature feature_type);
    [...] user_sdo_geom_metadata [...]
    Then
    CREATE INDEX features_idx ON features(feature.shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX;
    throws:
    ORA-01418: specified index does not exist
    Curious! :)
    If I define feature_type with "NOT FINAL" option but without subtypes, I get (create index):
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01460: unimplemented or unreasonable conversion requested
    So I think besides object tables also inheritance isn't supported whith oracle spatial!?
    Thanks,
    Michael
    ps:
    We use Oracle9i Enterprise Edition Release 9.0.1.4.0 / Linux.
    Solves Oracle9i 9.2 this problems?

    Hi
    You'll need to be on 9.2 to do this....
    Dom

  • Private attributes and Inheritance.

    I have a question regarding 'private attributes and inheritance'.
    If I have a class that will be extended by other classes,(basically
    this will act as a BASE class ),then why do I need to define
    any attribute private to this base class.?
    If I define an attribute as private in the base class,then the subclass cannot access
    this attribute.Right?
    1) Why define a private attribute in the base class ?
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?

    If I define an attribute as private in the base
    class,then the subclass cannot access
    this attribute.Right?Right. A simple example would tell you this.
    >
    1) Why define a private attribute in the base class?Because information hiding and encapsulation are always good things, even between super and sub classes.
    >
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?This question makes no sense whatsoever. A base class is extensible, unless it is marked as final, whether or not it's got private data members.
    Objects usually have private state and public interfaces. The idea is that clients of a class, even subclasses, should only access the private state thorugh the public interface. So if you've designed your classes properly you shouldn't need to access that private state.
    If you do, you can always provide get/set methods.
    OR declare the data members as protected. That way they're package visible and available to subclasses.
    But private members do not make a class inextensible.
    %

  • Singletons and multithreading question

    Hi, I had a class created as a singleton as it was only used in one place. However since Ive now multithreaded the part of the program that calls the singleton code so it could be called twice at the same time.
    If the method being called initializes all its variables within the method, is that method safe to be called in a mutli-threaded env or not ?
    If it in my situation all variables are declared within the method except a precompiled javax.xml.XPathExpression class, the same one is used to parse an Input Source, the input source itself is created within the method. I
    think I am having concurrency problems , (SAXParser Exceptions) and I think it is because of this XPathExpression class but cannot clearly understand why.
    What is the correct solution, I dont want to initilize the XPathExpression within the method because the method is called many times always for the same expression, dropping the singleton and creating new instances of the class on every call would be even worse. I require multithreading to improve concurrency is there a safe Multi Singleton pattern that i should be using ?

    There are two issues:
    a) is the singleton object safe for multithreaded use
    b) how do I safely create a singleton in a multi-threaded application
    The answer to (a) depends on the class. It sounds from your description that you are using an object (the XPathExpression) that might not be thread-safe. I can't tell you if it is or not. Assuming it is not you either need to synchronize this method so that all threads will go through it (and use the expression) one at a time - which may defeat the purpose of multi-threading - or else you need a way to use multiple instances of these expressions in different threads. As I'm not familiar with these classes I can't tell you what you can and can't do concurrently.
    There are a number of answers to (b). Construction via static initialization is the simplest and safest. If you want lazy initialization and the class that holds the reference to the singleton must be loaded even if the singleton isn't needed, then lookup the initialize-on-demand-holder-class idiom (see Josh Bloch's "Effective Java" item 48)

  • What's the differences between a singleton and a class with static methods

    Hi everybody.
    My question is in the subject. Perhaps "differences" is not the good word. The positive and negative points ?
    Imagine you have to write a connection pool, sure you gonna choose a singleton but why ?
    Thank you very much.

    A class is a class. Java doesn't have (and I wish it
    did) a static outer class. Any class can extend
    another class or implement an interface.A Class object cannot extend or implement anything - it is not under programmer control in any way. You can create a class which implements interfaces, but calling static methods is completely unrelated. Interfaces only affect instance methods, not class ones. I think all of your comparison to C++ is actually confusing you more. In Java, there is a real class object at runtime, as opposed to C++.
    YATArchivist makes a good point about being able to
    serialize, altho I've not met that desire in practice.
    Maybe a concrete example would help.
    mattbunch makes another point that I don't understand.
    A class can implement an interface whether it sticks
    its data in statics or in a dobject, so I guess I
    still don't get that one.See my comment above. Static methods are free from all contractual obligations.
    I prefer instance singletons to singleton classes because they are more flexible to change. For instance I created a thread pool singleton which worked by passing the instance around, but later I needed two thread pools so I made a slight modification to the class and poof! no more singleton and 99% of my code compiled cleanly against it.
    When possible, I prefer to hand the instance off from object to object rather than have everything call Singleton.instance() since it makes changes like I mentioned earlier more feasible.

  • Imported and Inherited properties

    Hi ,
    Can anyone please explain me what are the imported and inherited properties in OCD?
    How are they created?

    You can try running following query in your instance.
    SELECT f.*
    FROM cz_xfr_fields f, cz_xfr_tables t
    WHERE t.order_seq=f.order_seq
    AND t.dst_table='CZ_PROPERTIES'
    AND f.xfr_group='IMPORT'
    AND t.xfr_group=f.xfr_group
    AND f.dst_field='DEF_VALUE';
    SELECT f.*
    FROM cz_xfr_fields f, cz_xfr_tables t
    WHERE t.order_seq=f.order_seq
    AND t.dst_table='CZ_PROPERTIES'
    AND f.xfr_group='IMPORT'
    AND t.xfr_group=f.xfr_group
    AND f.dst_field='PROPERTY_UNIT'
    If the NOUPDATE field returns value 1, then update it to 0 by preparing appropriate UPDATE query for it.

  • Logical Database PNPCE and inherited Sub Area

    Hi,
    I have asked this in the HR forum but no response......
    I have a report using Logical Database PNPCE to find some values from a couple of info types. When I select a unit (from the 'OrgStructure' button at the top of the screen), say 111, and all its sub-units with no selections in the selection screen, I get one person displayed. This is correct and this person is in a sub-unit 3 levels down (unit 333).
    I then added a selection to only display people in units with Personnel SubArea 'OTEC'. Now I get no results output. When I look in PPOME, I can see that unit 333 has Personnel SubArea 'OTEC' but it is inherited from '111'.
    In PP01, unit 111 has an Account Assignment entry (Info Type 1008) but 333 does not.
    Does anyone know how to report on this?
    Is there a flag somewhere that tells the LDB to check for inherited units?
    If not, any ideas if there is a function out there to find the superior unit for these sub-units?
    Thanks.

    Thanks,
    I am aware of that FM but how do I find the parent unit in a clever fashion?
    The structure could have multiple levels e.g.
    Unit 1 - Unit 2a - Unit3a......
           - Unit 2b
           - Unit 2c
    Unit 1 is the parent and all the below units inherit from it.
    The LDB is looping through an internal table with a list of the units. It finds Unit 1 but not the rest.
    So, when the LDB is looking for Unit 3a, how does it know that Unit 1 is the parent?
    If I use that FM, I think I would have to look for all units above it and see if there is an Info Type 1008 exists. Seems like a lot of processing for something that should be simple?
    Kroc.

  • I worked for a company that closed down and inherited an ipad 2 linked to Vodafone uk as the carrier but no account details. So I factory reset, downloaded the ios7and added EE sim and Ipad does not work. what can I do? Voda/EE/Apple say NO SOLUTION?

    I inherited an Ipad 2 from a company that I had worked for in the UK but had closed down.
    It was an IPAD2 locked to the Vodafone UK network by a Vodafone SIM Card.
    No account details were or are available for the original account.
    So I removed the Vodafone SIM Card and then factory reset wirelessly using my wireless at home.
    I updated the system to IOS 7.0.2.
    I was then sold under a contract from EE another UK carrier a SIM card for the Ipad and when inserted the Ipad says Sim not applicable.
    I checked with Vodafone and EE shop and they said they cant unlock it, I checked with Apple who said the same!
    So I have an IPad I can use wirelessly at home, a sim card from EE which is an u
    locked Vodafone carrier mode and all 3 multinational companies say they cannot unlock it from Vodafone to enable me to use the EE sim.
    What can I do to sort this mess out? Please help!
    Thank You

    Steve, have you tried just going through the unlock form here?
    http://www.vodafone.co.uk/vodafone-uk/forms/unlock-code-request/
    That's what the moderator in several older threads in Vodaphone's forum said was all that is necessary. Carriers often won't unlock for anyone but the original account holder, so if you don't have the details of the company's account, that might be the barrier in which case there will not be any way to get the iPad officially unlocked.
    Good luck.

Maybe you are looking for