1-explain singleton pattern in java2-explain up casting and down casting3-how do u code a singleton in java4-How do u read XML file in java5-gine an example of the Decorator pattern in the java API.6-What r the services provided by the container? 7-what r bean managed transaction?8-what r transaction attributes?9-what is JTS?

Showing Answers 1 - 7 of 7 Answers

Marvin_mage

  • Dec 19th, 2005
 

The singleton design pattern is designed to restrict instantiation of a class to one (or a few) objects. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.

The singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If one does exist it returns a reference to the object that already exists. To make sure that the object cannot be instantiated any other way the constructor is made either private or protected.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.

A Java programming language solution is as follows. It is based on the Q&A link found below, modified for multi-threading, however, it is still vulnerable to the double-checked locking anti-pattern, also found below:

public class Singleton {
    private static Singleton INSTANCE = null;

    // Private constructor suppresses
    // default public constructor
    private Singleton() {}

    //synchronized creator to defend against multi-threading issues
    //another if check here to avoid multiple instantiation
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
    }

    public static Singleton getInstance() {
        if (INSTANCE == null) createInstance();
        return INSTANCE;
    }
}

  Was this answer useful?  Yes

YON

  • Feb 15th, 2006
 

As we all know there are 23 design patterns all together.Design patterns in Java mainly classified into 3 types1. CREATIONAL PATTERNS 2. STRUCTURAL PATTERNS3. BEHAVIORAL PATTERNS1 .Under Creational Patterns we have 1.Factory Pattern 2.Abstract Factory Pattern 3.Singleton Pattern 4.Builder Pattern 5.Prototype Pattern This is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class.It is easier to use

  Was this answer useful?  Yes

YON

  • Feb 15th, 2006
 

This is one example that i have got it in one of the leading websites...guys this would be helpful------------------------------------------------------------------------------------------------------------------------------------This is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class. Let?s take up an example to understand this.A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.package creational.singleton; import org.apache.log4j.Priority;import java.text.SimpleDateFormat;import java.util.GregorianCalendar;import java.util.Properties;import java.io.InputStream;import java.io.FileOutputStream;import java.io.PrintStream;import java.io.IOException;public class Logger { private String fileName;private Properties properties;private Priority priority; /*** Private constructor*/private Logger() {logger = this;}/*** Level of logging, error or information etc** @return level, int*/public int getRegisteredLevel() {int i = 0;try {InputStream inputstream = getClass().getResourceAsStream("Logger.properties");properties.load(inputstream);inputstream.close();i = Integer.parseInt(properties.getProperty("**logger.registeredlevel**"));if(i < 0 || i > 3)i = 0;}catch(Exception exception) {System.out.println("Logger: Failed in the getRegisteredLevel method");exception.printStackTrace();}return i;}/*** One file will be made daily. So, putting date time in file* name.** @param gc GregorianCalendar* @return String, name of file*/private String getFileName(GregorianCalendar gc) {SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy");String dateString = dateFormat1.format(gc.getTime());String fileName = "C:\\prashant\\patterns\\log\\PatternsExceptionLog-" + dateString + ".txt";return fileName;}/*** A mechanism to log message to the file.** @param p Priority* @param message String*/public void logMsg(Priority p, String message) {try {GregorianCalendar gc = new GregorianCalendar();String fileName = getFileName(gc);FileOutputStream fos = new FileOutputStream(fileName, true);PrintStream ps = new PrintStream(fos);SimpleDateFormat dateFormat2 = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss a");ps.println("<"+dateFormat2.format(gc.getTime())+">["+message+"]");ps.close();}catch (IOException ie) {ie.printStackTrace();}}/*** this method initialises the logger, creates an object*/public static void initialize() {logger = new Logger();}// singleton - patternprivate static Logger logger;public static Logger getLogger() {return logger;}}// End of classDifference between static class and static method approaches:One question which a lot of people have been asking me. What?s the difference between a singleton class and a static class? The answer is static class is one approach to make a class ?Singleton?.We can create a class and declare it as ?final? with all the methods ?static?. In this case, you can?t create any instance of class and can call the static methods directly.Example:final class Logger {//a static class implementation of Singleton patternstatic public void logMessage(String s) {System.out.println(s);}}// End of class//==============================public class StaticLogger {public static void main(String args[]) {Logger.logMessage("This is SINGLETON");}}// End of classThe advantage of this static approach is that it?s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.

  Was this answer useful?  Yes

YON

  • Feb 15th, 2006
 

In a bean-managed transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have bean-managed transactions; it must use container-managed transactions instead. Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.

  Was this answer useful?  Yes

YON

  • Feb 15th, 2006
 

Hi CyberWizards,This is one small example about that Decorator pattern which belongs to Structural Patterns.Structural Patterns - Decorator PatternThe decorator pattern helps to add behavior or responsibilities to an object. This is also called ?Wrapper?. Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.Java Design Patterns suggest that Decorators should be abstract classes and the concrete implementation should be derived from them.The decorator pattern can be use wherever there is a need to add some functionality to the object or group of objects. Let?s take an example of a Christmas tree. There is a need to decorate a Christmas tree. Now we have many branches which need to be decorated in different ways.Let?s have a look at the basic Decorator class.Decorator.javapackage structural.decorator;public abstract class Decorator { /** The method places each decorative item* on the tree.*/public abstract void place(Branch branch);}// End of classThis class has just one method place(). This method places different types of items on the branches of the tree.The class ChristmasTree is very simple and has just one method which returns a branch.ChristmasTree.javapackage structural.decorator;public class ChristmasTree { private Branch branch;public Branch getBranch() {return branch;}}// End of classNow we can decorate the branches in three different ways, one is by putting coloured balls on them, by putting coloured ruffles on them and also by putting stars on them.Let?s have a look at the implementation of these three different types of decorators.BallDecorator.javapackage structural.decorator;/*** Decorates the branch of the tree with* coloured balls.*/public class BallDecorator extends Decorator { // Default Constructorpublic BallDecorator(ChristmasTree tree) {Branch branch = tree.getBranch();place(branch);}/** The method places each decorative item* on the tree.*/public void place(Branch branch) {branch.put("ball");}}// End of classSimilarly, we can make StarDecorator and RufflesDecorator. Now, we will see how to use the decorator. Its simple, we just are needed to pass the instance of ChristmasTree class to a decorator.StarDecorator decorator = new StarDecorator(new ChristmasTree());This way the decorator will be instantiated and a branch of the Christmas tree will be decorated.This is a very abstract example and could not be implemented in terms of code fully. But, then, as I have said, I want you to understand the patterns rather than giving you concrete examples. Once the pattern is internalized, you can think of some good software examples yourself.Decorators, Composites and AdaptersThe decorator and adapter patterns are similar. Adapters also seem to decorate the classes. The intent of using adapter is to convert the interface of one or more classes to suit the interface of the client program. In case of decorator, the intent is to add behavior and functionality to some of the objects, not all the objects or adding different functionalities to each of the objects.In case of composite objects, the client program treats the objects similarly, whether it is a simple or complex object (nodes).The decorator pattern provides functionality to objects in a more flexible way rather than inheriting from them.There is however disadvantage of using decorator. The disadvantage is that the code maintenance can be a problem as it provides the system with a lot of similar looking small objects (each decorator). PatternsCreational PatternsFactory Pattern Abstract Factory Pattern Singleton Pattern Builder Pattern Prototype PatternStructural PatternsAdapter Pattern Bridge Pattern Composite Pattern Decorator Pattern Facade Pattern Flyweight Pattern Proxy PatternBehavioral PatternsChain of Responsibility Pattern Command Pattern Interpreter Pattern Iterator Pattern Mediator Pattern Momento Pattern Observer PatternState Pattern Strategy Pattern Template PatternVisitor PatternAll the very best folks ------ Regards,YON

  Was this answer useful?  Yes

YON

  • Feb 15th, 2006
 

Hi Folks,The Enterprise JavaBeans model supports six different transaction attributes: ##TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the enterprise bean manually manages its own transaction control. EJB supports manual transaction demarcation using the Java Transaction API. This is very tricky and should not be attempted without a really good reason. ##TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the enterprise bean cannot execute within the context of a transaction. If a client (i.e., whatever called the method-either a remote client or another enterprise bean) has a transaction when it calls the enterprise bean, the container suspends the transaction for the duration of the method call. ##TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean can run with or without a transaction context. If a client has a transaction when it calls the enterprise bean, the method will join the client's transaction context. If the client does not have a transaction, the method will run without a transaction. ##TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean must execute within the context of a transaction. If a client has a transaction when it calls the enterprise bean, the method will join the client's transaction context. If the client does not have a transaction, the container automatically starts a new transaction for the method. Attributes ## TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the enterprise bean must execute within the context of a new transaction. The container always starts a new transaction for the method. If the client has a transaction when it calls the enterprise bean, the container suspends the client's transaction for the duration of the method call. ## TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise bean must always execute within the context of the client's transaction. If the client does not have a transaction when it calls the enterprise bean, the container throws the TransactionRequired exception and the request fails.

  Was this answer useful?  Yes

Ramesh Chowdary

  • Oct 4th, 2006
 

explain singleton pattern in java:

Singleton is a interface.it is a marker inerface means it did not contain any method declarations.

we can create only single instance for that class not possiable to create more then one instance.

Ex:

class sample

{

private static sample instance=null;

private sample

{

}

public synchronized static sample getInstance()

{

    if(instance==null)

    {

         instance=new sample();

      }

     return instance;

}

}

explain up casting and down casting?

Upcasting: Converting lower to upper. Giving subclass reference to super class.

A a=new A()//Super

B b=new B()//sub

a=b;//Upcasting

DownCasting: Converting upper to lower.Giving superclass reference to suclass.

A a=new A()//Super

B b=new B()//sub

a=b;

b=(B)a;//downCasting

How do u read XML file in java

To read xml file in java we have to use parsers.we have two type of parsers .those are DOM(document object model) parser,SAX(Simple API for xml) parser.We can use any one for reading purpose.

Ex:

Class sample

{

     public static void main(Stirng args[])

      {

          Parser p=new Parser("MyErrors");

          FileInputStream fis=new FileInputStream("emp.xml");

         TXDocument td=p.readStream(fis);

      }

}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions