Java class that return itself - java

I need a class able to return instances of itself. I like method used by a singleton pattern that return only once instance of class. But I need that it return more than one instance.
This is my singleton pattern. How can I modify it to get it able to return more than one instance?
public class GrigliaImpl implements Griglia{
private static GrigliaImpl istanza;
private JTextField[][] griglia;
private Color color;
public GrigliaImpl(){
}
#Override
public int getColumn() {
return griglia[0].length;
}
public JTextField[][] getMatrice(){
return this.griglia;
}
#Override
public int getRow() {
return griglia.length;
}
#Override
public void setColor(Color x) {
this.color=x;
}
#Override
public Color getColor() {
return color;
}
public void set(int row,int column){
this.griglia= new JTextField[row][column];
}
public static GrigliaImpl getIstanza(){
if(istanza == null){
istanza = new GrigliaImpl();
}
return istanza;
}
}

You are talking about the factory pattern:
public class MyClass() {
}
public class MyClassFactory() {
public static getNewInstance() {
return new MyClass();
}
}
The factory method can be included in your class, you don't need a separate factory class.

Your requirements are controversial. If you want to have a singleton - then you will have one instance of this class by definition. If you want to have many instances, then it can't be singleton.
To create a singleton, you need to make your constructor private and add static method to get an instance of your class, which is kept as a static field. (http://en.wikipedia.org/wiki/Singleton_pattern)
If you want to return the same instance of class, after invoking its methods, consider using Builder pattern (http://java.dzone.com/articles/dive-builder-pattern).
public class GrigliaImpl implements Griglia {
private static GrigliaImpl instance;
private GrigliaImpl() {
}
public static GrigliaImpl getInstance() {
if (instance == null) {
instance = GrigliaImpl();
}
return instance;
}
public GrigliaImpl doSomething() {
// do something
return this;
}
}

Default behavior of every class that has a public contructor is to create and return new instances of that class using new operator. but if you specifically want instances through a getInstanceMethod than make constructor private and
replace
public static GrigliaImpl getIstanza(){
if(istanza == null){
istanza = new GrigliaImpl();
}
return istanza;
}
with
public static GrigliaImpl getIstanza(){
return new GrigliaImpl();
}
But to me that does not serve any purpose. But you can still do it :)

Related

What is the functional difference between these two definitions?

// in PingPongMessage.java
public class PingPong {
public static final class Ping { }
}
// in PingActor.java
public class PingActor extends AbstractBehavior<PingPong.Ping> {
public static Behavior<PingPong.Ping> create() {
return Behaviors.setup(context -> new PingActor(context));
}
private PingActor(ActorContext<PingPong.Ping> context){
super(context);
}
#Override
public Receive<PingPong.Ping> createReceive() {
return newReceiveBuilder().onMessage(PingPong.Ping.class, this::onPingMsg).build();
}
private Behavior<PingPong.Ping> onPingMsg() {
System.out.println("Ping!");
return this;
}
}
vs.
// in PingActor.java
public class PingActor extends AbstractBehavior<PingActor.Ping>{
public static final class Ping {
}
public static Behavior<Ping> create() {
return Behaviors.setup(context -> new PingActor(context));
}
private PingActor(ActorContext<Ping> context){
super(context);
}
#Override
public Receive<Ping> createReceive() {
return newReceiveBuilder()
.onMessage(Ping.class, this::onPingMessage).build();
}
private Behavior<Ping> onPingMessage(Ping message){
System.out.println("Ping!");
return this;
}
}
I am trying to understand the relationship between Ping and PingActor in both the cases. In my opinion both are doing the same thing, but in one case PingPong.Ping is defined inside PingActor and in the other case PingPong is another class outside of it. Obviously they are not the same because the second example seems to compile, but the first does not.
The compiler error is -
Inferred type 'M' for type parameter 'M' is not within its bound; should extend 'com.lightbend.akka.sample.PingPong.Ping seen in Receive<PingPong.Ping> createReceive()
You cannot have a public class "PingPong" inside PingPongMessage.java
They don't match

Choosing between extended classes inside constructor

I am writing a java (processing) library for unexperienced students, and am looking for the best architecture for implementing it.
Initialization of an object should be as close as possible to this:
myObject = new General("type1");
Such that myObject will become an instance of Type1 which extends General:
class General {
public General() {}
}
class Type1 extends General {
public Type1() {}
}
class Type2 extends General {
public Type1() {}
}
As far as I know, this isn't possible (choosing between extended classes during initialization), but I'm looking for the closest solution possible.
So far, my best solution is to make a static initializer inside General:
class General {
...
static General init (String type) {
General temp;
if (type.equals("type1") {
temp = new Type1();
}
...
return temp;
}
and the initialization is:
General myObject;
myObject = General.init("type1");
This is far from ideal...
thanks.
you can make a factory class that manages initialization.
instead of doing it inside the parent.
// Empty vocabulary of actual object
public interface IPerson
{
string GetName();
}
public class Villager : IPerson
{
public string GetName()
{
return "Village Person";
}
}
public class CityPerson : IPerson
{
public string GetName()
{
return "City Person";
}
}
public enum PersonType
{
Rural,
Urban
}
/// <summary>
/// Implementation of Factory - Used to create objects.
/// </summary>
public class Factory
{
public IPerson GetPerson(PersonType type)
{
switch (type)
{
case PersonType.Rural:
return new Villager();
case PersonType.Urban:
return new CityPerson();
default:
throw new NotSupportedException();
}
}
}
The State design pattern can be a solution here. Rather than the constructor argument changing the type of the object (which isn't possible) it can set a field of the object, to make it behave as if its type is different.
package stackoverflow.questions;
public class Main {
private interface MyInterface {
String foo();
int bar();
}
private static class Type1 implements MyInterface {
#Override public String foo() { return "lorem ipsum "; }
#Override public int bar() { return 6; }
}
private static class Type2 implements MyInterface {
#Override public String foo() { return "dolor sit amet"; }
#Override public int bar() { return 7; }
}
public static class General {
private final MyInterface type;
public General(String type) {
try {
this.type = (MyInterface) Class
.forName("stackoverflow.questions.Main$" + type)
.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new IllegalArgumentException("Invalid type: " + type);
}
}
public String method1() { return type.foo(); }
public int method2() { return type.bar(); }
}
public static void main(String... args) {
General one = new General("Type1");
General two = new General("Type2");
System.out.println(one.method1() + two.method1());
System.out.println(one.method2() * two.method2());
}
}

Best practices in two class

if i need use a global class what is the best option and why?
public class Global {
public static JSONObject GetJsonResquest(String url){
....
};
}
and then call Global.GetJsonResquest(url) in my activity
OR
public class Singleton {
private static Singleton ourInstance = new Singleton();
public static Singleton getInstance() {
return ourInstance;
}
private Singleton() {
}
public JSONObject GetJsonResquest(String url){
.....
}
}
and then use via Singleton.getInstance().GetJsonResquest("Asd");
When I need a global static variable, I like to group them into a class like
public class MyConstants {
public static final int TIMEOUT = 10000;
}
To use it, i can call it like
long tick = System.currentThreadMillis();
while((System.currentThreadMillis() - tick) < MyConstants.TIMEOUT){
Thread.sleep(1000);
}
So that when I change the TIMEOUT value, I don't have to change other classes that calls it
For global static method, I use them like
public class Utility{
public static boolean isStringValidJson(String jsonString){
return false;
}
}
Same reason as above. When I change isStringValidJson, other classes that calls it don't change
I do use the singleton pattern but only when I override the Application class. However, I set the instance value in OnCreate instead. This means that if OnCreate was not called, getInstance will return null
public class MyApplication extends Application {
private static MyApplication instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static synchronized MyApplication getInstance(){
return instance;
}
}

Change return value of final class in tests

Does somebody know how to change the return value of the method in the final class.
I'm trying to test the ToBeTested class and I want to get true as the result.
I tried to use Powermockito but didn't find a solution.
public final class ToBeChanged {
public static boolean changeMyBehaviour() {
return false;
}
}
public class ToBeTested {
public boolean doSomething () {
if (ToBeChanged.changeMyBehaviour)
return false;
else
return true;
}
}
I do not want to declare the ToBeChanged class as a field in the ToBeTested class.
So there is no way to change the implemented classes itself.
With the JMockit tool, the test would be like this:
#Test
public void doSomething(#Mocked ToBeChanged mock)
{
new NonStrictExpectations() {{ ToBeChanged.changeMyBehaviour(); result = true; }};
boolean res = new ToBeTested().doSomething();
assertTrue(res);
}
Hide the static dependency behind an interface. Mock the interface.
Since you don't want to have a field on your class, simply pass the interface as a method parameter (alternatively get an instance through a factory, just don't use tight coupling)
public final class ToBeChanged {
public static boolean changeMyBehaviour() {
return false;
}
}
public interface MyInterface {
boolean changeMyBehaviour();
}
public class MyInterfaceImpl implements MyInterface {
#Override
public boolean changeMyBehaviour() {
return ToBeChanged.changeMyBehaviour();
}
}
class ToBeTested {
public boolean doSomething (MyInterface myInterface) {
return !myInterface.changeMyBehaviour();
}
}
class TheTest {
#Test
public void testSomething() {
MyInterface myMock = mock(MyInterface.class);
when(myMock.changeMyBehaviour()).thenReturn(true);
new ToBeTested().doSomething(myMock);
}
}

Singleton Lazy Loading Pattern

I am trying to write a Singleton Lazy Loading Pattern. Here is the class:
public class IMDBLookup {
private static class LazyLoad {
private static final IMDBLookup IMDB_LOOKUP;
static {
IMDB_LOOKUP = new IMDBLookup();
}
}
public static IMDBLookup getInstance() {
return IMDBLookup.LazyLoad.IMDB_LOOKUP;
}
}
I am wondering whether or not I am doing it in a right way?
Thanks in advance.
I prefer to use enum for simplicity.
public enum IMDBLookup {
INSTANCE;
// add fields and methods here.
}
That is correct. You may want to simplify the inner (holder) class as private static final IMDBLookup IMDB_LOOKUP = new IMDBLookup(); for brevity (to get rid of the static initializer block.)
public class IMDBLookup {
private IMDBLookup(){
// without this I do not get why is it a singleton
// anyone could create instances of your class by the thousands
}
private static class LazyLoad {
private static final IMDBLookup IMDB_LOOKUP;
static {
IMDB_LOOKUP = new IMDBLookup();
}
}
public static IMDBLookup getInstance() {
return IMDBLookup.LazyLoad.IMDB_LOOKUP;
}
}
and you should probably use an enum (not completely sure I do this right)
public class IMDBLookup {
private IMDBLookup(){
}
private static enum LazyLoad {
IMDB_LOOKUP_INSTANCE;
private static final IMDB_LOOKUP = new IMDBLookup();
}
public static IMDBLookup getInstance() {
return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
}
}
The advice you to think about clone & serialize
import java.io.Serializable;
public class DBConnectionInner implements Cloneable, Serializable {
private static final long serialVersionUID = 1173438078175185035L;
#Override
protected Object clone() throws CloneNotSupportedException {
return new CloneNotSupportedException("CLONE NOT SUPPORT FOR SINGTELTON");
}
protected Object readResolve() {
return getInstance();
}
private DBConnectionInner() {}
static DBConnectionInner getInstance() {
System.out.println("DBConnectionInner getInstance");
return LazyInit.instance;
}
public static class LazyInit {
private static final DBConnectionInner instance = new DBConnectionInner();
}
}

Categories

Resources