Start here

Singleton Pattern in java

Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.

There are only two points in the definition of a singleton design pattern,

  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.

GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.

The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.

package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }

You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.

package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

The greatest problem in application design is a lack of forethought. As it applies to database-driven
applications, the design process must include a thorough evaluation of your database —what it should
hold, how data relates to each other, and most importantly, whether it is scalable.
The general steps in the design process are :
         Define the objective.
    •
         Design the data structures (tables, fields).
    •
         Discern relationships.
    •
         Define and implement business rules.
    •
         Create the application.
    •
Creating the application is the last step—not the first! Many developers take an idea for an application,
build it, and then go back and try to make a set of database tables fit into it. This approach is
completely backward, inefficient, and will cost a lot of time and money.
Before you start any application design process, sit down and talk it out. If you can't describe your
application—including the objectives, audience, and target market—then you're not ready to build it, let
alone model the database.
After you can describe the actions and nuances of your application to other people and have it make
sense to them, you can start thinking about the tables you want to create. Start with big flat tables
because, after you write them down, your newfound normalization skills will take over. You will be
able to find your redundancies and visualize your relationships.
The next step is to do the normalization. Go from flat table to first normal form and so on up to the
third normal form if possible. Use paper, pencils, sticky notes, or whatever helps you to visualize the
tables and relationships. There's no shame in data modeling on sticky notes until you're ready to create
the tables themselves. Plus, using them is a lot cheaper than buying software to do it for you; software
ranges from one hundred to several thousands of dollars!
After you have a preliminary data model, look at it from the application's point of view. Or look at it
from the point of view of the person using the application you're building. This is the point where you
define business rules and see whether your data model will break. An example of a business rule for an
online registration application is, "Each user must have one e-mail address, and it must not belong to
any other user." If EmailAddress wasn't a unique field in your data model, your model would be broken
based on the business rule.
After your business rules have been applied to your data model, only then can application programming
begin. You can rest assured that your data model is solid and you will not be programming yourself into
a brick wall. The latter event is all too common.

Tshirt biz

hey people am designing cool kenyan t shirts with nelly contacts…0751985530

Loving Javafx – Rich Internet Application Development with JavaFX

Rich visual experience and interactivity are crucial features for cutting edge applications today, which boosts Rich Internet Application development. JavaFX stands in line with such RIA development tools as Ajax, Silverlight and Adobe Air and empowers software development companies to take advantage of their Java expertise to build and deploy stunning Rich Internet Applications. The JavaFX platform incorporates well into the Java development expertise and enables Java developers to make use of their existing knowledge and tech savvy for the development of Rich Internet Applications. Overview of core JavaFX features: JavaFX supports the Java programming language, which allows software developers feel comfortable using their preferable development technologies for RIA projects. JavaFX provides support for various platforms and devices, which ensures easy development both for desktop and browser-resided apps. Moreover, the JavaFX platform gives Java programmers an opportunity of RIA development for mobile devices. JavaFX comprises a wide range of APIs that facilitate RIA development for desktop and mobile, enable easy work with graphic components and UI elements and allow professional developers to harness other than JavaFX Script programming languages: JRuby, Groovy and JavaScript. JavaFX enables Java developers to employ third-party tools for elaborating graphical elements during the development and deployment of Rich Internet Applications (Adobe Photoshop, Illustrator etc). JavaFX ensures smooth and handy development as the JavaFX platform embraces graphics, media and web engines. JavaFX allows Java developers freely make use of HTML5, CSS, DOM and SVG owing to the in-build JavaFX browser, which streamlines RIA development process. JavaFX enables easy and fast threads handling and event management with the help of its Glass Windowing Toolkit. This JavaFX component is often leveraged by Java professionals during the RIA development process. Therefore, the JavaFX platform provides a holistic approach for cross-platform RIA development and ensures interoperability of Rich Internet Applications

Android voice search inspires new Google search tools

Mobile has been a new frontier for search tools, incurring cutting-edge ways to find the information you need. For Android phones in particular, voice search was an early addition, and mobile devices also seemed like perfect controls for on-the-go image search. So it’s nice to see these mobile search advancements encouraging improvements on the desktop, as Google (GOOG) adds voice and image search to its websites. The new desktop capabilities add more natural search tactics for Google’s massive search service, which has evolved with the times and technology since Google first came into existence. Mobile devices continue to encourage new ways of searching for things, from retail to mobile apps. A recent study shows the importance of search for mobile shoppers, reporting that a third of consumers have used their mobile phones from inside a physical store to access promos and coupons, or researching prices, ratings and reviews. The same report indicates increasing comfort levels with mobile scanning functions, with a third of survey respondents using QR or bar codes to get product information. And as Microsoft (MSFT) works with Nokia (NOK) towards its own mobile platform, its Bing search service is working its way deeper into the mobile realm, recently incorporating apps into the Bing app’s default search results. Consumers’ mobile inspiration Near Field Communications (NFC) has also been an inspiring aspect of mobile’s technological advancements, but it’s still in its infancy. Large brands like Starbucks (SBUX) are finding ways around this, launching payment apps of their own. The coffee retailer has extended its mobile payment system to Android phones, after the success of the app on the iPhone and BlackBerry. The new Android app lets you pay for transactions with your phone at various Starbucks locations, including Safeway (SWY), Target (TGT) and stand-alone locations. Mobile carriers are also seeking more ways to spur consumer activity, as T-Mobile’s new Android app delivers daily deals based on your location. The new app, called More for Me, aggregates daily deals from companies like LivingSocial, featuring discounts on restaurants, spas, retailers, concerts and more. The app has a social scheme, prompting users to share deals directly with Facebook friends and beyond. T-Mobile’s rather hopeful about this app, making it available to all Android users, not just T-Mobile customers, with plans to expand to BlackBerry and Windows phones.

Testing

It works

Date validation with java

Hi ya'll JDevs..I have a code snippet below that would help you solve problems in date validation.
Its a method that takes a string parameter as date and uses the SimpleDateFormat library to validate the date
Enjoy....
// date validation using SimpleDateFormat
// it will take a string and make sure it's in the proper
// format as defined by you, and it will also make sure that
// it's a legal date

public boolean isValidDate(String date)
{
    // set date format, this can be changed to whatever format
    // you want, MM-dd-yyyy, MM.dd.yyyy, dd.MM.yyyy etc.
    // you can read more about it here:
    // http://java.sun.com/j2se/1.4.2/docs/api/index.html

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    // declare and initialize testDate variable, this is what will hold
    // our converted string

    Date testDate = null;

    // we will now try to parse the string into date form
    try
    {
      testDate = sdf.parse(date);
    }

    // if the format of the string provided doesn't match the format we
    // declared in SimpleDateFormat() we will get an exception

    catch (ParseException e)
    {
      errorMessage = "the date you provided is in an invalid date" +
                              " format.";
      return false;
    }

    // dateformat.parse will accept any date as long as it's in the format
    // you defined, it simply rolls dates over, for example, december 32
    // becomes jan 1 and december 0 becomes november 30
    // This statement will make sure that once the string
    // has been checked for proper formatting that the date is still the
    // date that was entered, if it's not, we assume that the date is invalid

    if (!sdf.format(testDate).equals(date))
    {
      errorMessage = "The date that you provided is invalid.";
      return false;
    }

    // if we make it to here without getting an error it is assumed that
    // the date was a valid one and that it's in the proper format

    return true;

} // end isValidDate

:-D
:-D
Follow

Get every new post delivered to your Inbox.