How to Prevent instantiation of concrete classes? - java

Lets say I have a Record Interface and I can have N number of its concrete implementation classes eg. PropertyRecords,LoanRecords etc.How do I ensure there is no object of these N classes is created by client using new keyword?
Its quite easy if I have a single subclass;I can Make all the constructors package private;so that I can write a Factory class in the same package which will have a method which will be responsible for creating instances.But how to create a virtual Factory able to create several implementations of a single interface or abstract class.
Hope i am able to put myself correctly.Please ask if any clarification needed.
Thank you.

Not sure why you would want this, but your Factory class can use reflection to create instances like this:
public class RecordFactory {
public Record newInstance(Class<? extends Record> klass, Object... args) {
Constructor[] ctors = klass.getDeclaredConstructors();
// find the right constructor here..
return ctor.newInstance(args);
}
}
Then your clients can create instances like:
RecordFactory.newInstance(Loan.class, ...);

I'm not entirely sure I understand what you're trying to achieve (comment on this is not), but here are my thoughts:
Sounds like what you really want is to implement the Flyweight design pattern (http://en.wikipedia.org/wiki/Flyweight_pattern).
If you really want to implement this as you describe it (again, under the assumption that I understood correctly), the following should work:
public class Record {
private static final int MAX_INSTANCES = 20;
private static volatile int instanceCounter = 0;
private Record() {
if (instanceCounter >= MAX_INSTANCES)
throw new RuntimeException("max instances exceeded");
instanceCounter ++;
}
}

Related

Is it worth to put instance of class inside interface?

I'm trying to learn some basics about OOP in Java.
I read about interface. My question is: is it worth to use instances of class inside interface? I'm not sure, but I think it could reduce amount of instances among code, e.g:
public interface mergingInterface
{
ArrayClass ac = new ArrayClass();
LinkedListClass llc = new LinkedListClass();
}
then I just can do:
public class LinkedListClass implements mergingInterface
{
LinkedList link = new LinkedList();
public void filling()
{
ac.someMethodFromArrayClass();
//some method
}
}
and many classes may use one object. Is it worth? Is my thinking correct?
No! The point of an interface is that it's decoupled from its implementations. Any class should be able to implement it without having to modify it. In your example, you would have to modify mergingInterface to have an instance of every implementer.

How to implement a subclassable Singleton in Java

I am looking for a way to implement an abstract class (or effectively abstract) that enforces only one instance of each subclass.
I am fairly sure this would be pretty simple to implement with a Factory but I would be interested to know if it can be done without knowing all subclass types, i.e a generic singleton enforcer class.
Right now I am mostly just playing around with the idea for something like this, So I am not looking for feedback that questions the design choice here.
The language I am working in is Java, but right now I am not necessarily worried about implementation details, Unless it is not possible in Java, then, of course, provide evidence that it is not possible.
I'm wondering what it is you are trying to do. A couple of possibilities spring to mind and knowing where this is heading might help.
Option 1
So you could try to use an enum type as your abstract base class. Each enumeration constant is then guaranteed by the language to be a singleton. The enum can have abstract methods which the constants implement. This will work but compilation unit an get very big and hard to navigate if you have a lot of implementing constants and a lot of abstract methods to implement. You could of course delegate some of the work to helper classes if it starts to get out of hand.
Option 2
You could do is get the base class constructor to check it's actual type and store it in a static HashSet (or similar). If an entry already exists then you have two instances of the same singleton. Something like
public abstract class BaseClass {
private static HashSet<Class<?>> instances = new HashSet<>();
protected BaseClass() {
checkInstances();
}
private synchronized void checkInstances() {
boolean duplicate = instances.add(getClass());
if (duplicate) {
throw new RuntimeException("Duplicate class " + getClass().getName());
}
}
}
The disadvantage of this is that the error occurs at runtime and the code isn't especially pretty and as you can see you may need to consider synchronization of the set
Option 3
Your final option is simply not to ask the base class to enforce this restriction. It should probably the job of the derived classes to decided if they are singletons or not. A private constructor in the derived class is the easiest way to do that.
Conclusion
Personally I'd implement either option 1 or option 3 as you won't get run-time failures.
First, a generic singleton doesn't make sense.
A parent class should not be responsible of retrieving and managing instances of its subclasses.
It creates a strong coupling in both ways (parent->child and child->parent).
Second, as shmosel says, subclassing a singleton (without special artifact) is not possible.
The key of the singleton pattern is the lack of ability to instantiate the class outside the singleton class, so no public constructor has to be provided.
In these conditions, how subclass the singleton class ?
To allow subclassing a singleton class, you must have a public constructor while ensuring that you have no more than one instance of the class.
Inversion of control containers such as Spring may do that (It is an example of special artifact).
As a side note, I don't consider access modifier tweaking such as the package-private modifier that could allow to subclass a singleton but the limitation of it is that the singleton would be a singleton only outside the package.
I wanted to say, that singletons are bad. But found this problem interesting, So I created what you want.
Here is the code
public static abstract class SingletonBase {
private static HashSet<SingletonBase> instances = new HashSet<>();
{
for (SingletonBase sb : instances) {
if (sb.getClass() == this.getClass()) throw new RuntimeException("there is already 1 instance");
}
}
public static <E> E getInstance(Class<E> clazz) {
if (!SingletonBase.class.isAssignableFrom(clazz)) {
throw new RuntimeException();
}
for (SingletonBase sb : instances) {
if (sb.getClass() == clazz) return (E) sb;
}
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private SingletonBase() {
instances.add(this);
}
}
static class SingletonTest extends SingletonBase{
}
static class SecondSingletonTest extends SingletonBase{
}
public static void main(String[] args) {
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SingletonTest.class));
for(int i=0;i<=10;i++)
System.out.println( SingletonBase.getInstance(SecondSingletonTest.class));
//throws exception, because we try to create second instance here
new SingletonTest();
}
There are some problems with approach of creating generic class which are solved here:
first, you cannot create more than one instance, so base class has to keep track of all instances, and when you try to create another one using new, it will throw exception. Second, you need to get instance for a specific class. If you dont want to create instance like this:
SingletonBase.getInstance(SecondSingletonTest.class)
You can create subclasses like this:
static class SingletonTest extends SingletonBase{
public static SingletonTest getInstance(){
return getInstance(SingletonTest.class);
}
}
There was also suggested to use ENUM approach, it is easy to implement, but breakes open closed principle from SOLID

Creator in Factory Method Pattern

source: https://en.wikipedia.org/wiki/Factory_method_pattern
This diagram really alludes to Factory Method Pattern?
Why do we need Creator? Look at code example:
interface Product{
public String getName();
}
class ConcreteProduct1 implements Product {
#Override
public String getName() {
return "I'm product 1";
}
}
class ConcreteProduct2 implements Product {
#Override
public String getName() {
return "Im product 2!";
}
}
// CREATOR HERE
interface Creator{
public Product createProuct(String productClass);
}
class ConcreteCreator implements Creator{
#Override
public Product createProuct(String productClass) {
if(productClass.equals("1"))
return new ConcreteProduct1();
else if(productClass.equals("2"))
return new ConcreteProduct2();
else
return null; //
}
}
public class Test {
public static void main(String[] args) {
Creator c = new ConcreteCreator();
Product product = c.createProuct("1");
System.out.print(product.getName());
}
}
Code without Creator interface:
class ConcreteCreator{
public Product createProuct(String productClass) {
if(productClass.equals("1"))
return new ConcreteProduct1();
else if(productClass.equals("2"))
return new ConcreteProduct2();
else
return null; //
}
}
public class Test{
public static void main(String[] args) {
ConcreteCreator c = new ConcreteCreator();
Product product = c.createProuct("1");
System.out.print(product.getName());
}
}
So why do we need Creator interface? Is it in case i would add another factory method in future? If yes, is it still Factory Method Pattern or Abstract Factory Pattern? Could you give me some code examples with extensions to my Creator interface and implementation of ConcreteCreator which uses two methods?
Also how about generic Creator? It looks much simpler than many type specified Creators...:
interface Product{
public String getName();
}
class ConcreteProduct implements Product{
#Override
public String getName() {
return "I'm product 1";
}
}
interface Moveable{
public String move();
}
class Car implements Moveable{
#Override
public String move() {
return "moving...";
}
}
interface Creator<T>{
public T create();
}
class ConcreteCreatorProducts implements Creator<Product>{
#Override
public Product create() {
return new ConcreteProduct();
}
}
class ConcreteCreatorCar implements Creator<Car>{
#Override
public Car create() {
return new Car();
}
}
public class Test{
public static void main(String[] args) {
Creator<Product> productCreator = new ConcreteCreatorProducts();
Product product = productCreator.create();
Creator<Car> carCreator = new ConcreteCreatorCar();
Car car = carCreator.create();
}
}
In your example, you don't need a Creator interface, unless you want to have multiple implementations and swap between them. But the diagram is actually describing a slightly different pattern than you've implemented.
The way the factory method pattern is described there is based on the original design patterns book. It's a bit odd today, as it uses subclassing to configure a class, when we would encourage the use of composition instead. So, the diagram does show the factory method pattern, but different from the way it's described in many other places.
The factory method pattern is:
Define an interface for creating an object, but let subclasses decide
which class to instantiate. The Factory method lets a class defer
instantiation it uses to subclasses.
In the original pattern, Creator isn't an interface. By 'interface', they mean the factory method that Creator defines, not interfaces like Java has.
The factory method doesn't need a parameter. Instead of different types being returned based on the parameter, there are different types returned based on the subclass created.
Also, you wouldn't call createProduct from main, but from methods within Creator. Creator is the user of the factory method, so it defines a factory method, that may be abstract, and some other methods that use that method.
See the Java examples on the wikipedia page. The MazeGame class is the Creator. The constructor is used as the anOperation method, and there are multiple subclasses for creating different kinds of rooms.
Code is written so that human readers understand it.
This means that you as a programmer sometimes use the means of the language not because it is absolutely mandatory, but because it is the best way to communicate your intention.
As soon as you declare that something is an interface you make it clear that there is no "base class" - only an interface, and that any specific implementation is subtle detail not really important to people dealing with the corresponding objects.
In other words: yes, it is perfectly possible to implement a factory pattern where the part responsible for creating the actual objects is not an interface, but a fixed class. Especially when thinking about "internal" factories (that are not exposed to a public API and wide range of "different" end users) that case is probably even the more common approach. ( the code I write contains many factories, few of them would follow the above approach of "interfacing" almost everything )
Beyond that - keep in mind that programming is also often about balancing between different requirements. Example: you might (again for communicating intent) decide to declare a class that provides a certain functionality as final. So that nobody gets idea of extending that specific class. But doing so means that users of that API are all of a sudden affected in their choice of mocking frameworks. As mocking final classes is not something that you can do easily. When you are then consuming this API, and you want to write unit tests - then you are very happy about the fact that the public API is relying on interfaces, not classes. Because you can always mock interfaces - but as said, final classes can cause headache.

Elegant way to create one of a large number of classes

For context, I'm trying to make a game something along the lines of Pokemon. You obtain, train and fight monsters.
Each species of monster is a class inheriting from an abstract base class (so they can have unique behaviour), and hopefully there will be a very large number of different species throughout the game. Ex:
abstract class Monster {
int hp;
void attack();
//Etc.
}
public class FireBreathingDragon extends Monster {
static String species_name = "Fire Breathing Dragon";
//Blah
}
So when the player is exploring, they will encounter monsters local to an area at random. The game then needs to create a monster at random from a list of species that live in that area. Now to make this code reusable between areas (and make it easy to create monsters dynamically in other places in the code) I don't want to hardcode the possibilities into the area. Instead I think I'd like something along the lines of a factory that creates a monster of a given species on demand, something like:
public class MonsterFactory {
Monster createMonster(
String species_name,
//Possibly other paramters
);
}
The problem is then implementing createMonster in a "nice" or "elegant" way when you have (potentially) tens or hundreds of different Monster classes. Of course you could use a very very long if-else if-else or switch statement, but that's horrible to write and extend. Is there a nice way to do this? It would also be good if it was relatively easy to extend when adding more monsters.
Or is there some totally different design I should be using instead?
Disclaimer: My java is a little rusty, syntax may not be perfect, sorry about that.
You could register all your Monster implementation classes in a List.
List<Class<? extends Monster>> monsterTypes = new LinkedList<>();
monsterTypes.add(FireBreathingDragon.class);
// more
This doesn't have to be hardcoded. You can externalize it to some XML, Json, or other file format.
The factory instance or class can then choose a monster type from the list at a random index. You can then use reflection to instantiate the type.
The simplest solution is to have a data driven monster class. This means you only have one class (or a small number) and this class can be used for a wide variety of monsters with different attributes and abilities.
You could have a CSV file which contains each species and all the attributes and abilities fr that species. This way you could add a species by adding a line in a spreadsheet.
This solution uses Class Factories without any form of reflection. Why is this important in the context of the question ("the most elegant way")? From a very interesting exchange with another contributor: I quote Sun/Oracle's Reflection API Tutorial "Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it." To justify this, Sun/Oracle's authors resort to extremely technical reasons internal to Java. I agree with them, but my main reason is long-term code maintenance and tooling. And what's the main alternative to reflection? Annotation-based automatic code generation. I can't do something like that in this short space, but I can produce what should be, more or less, the resulting code:
public interface Factory<T> {
T make();
}
public static class BasicMonster {
}
public static class Monster1 extends BasicMonster {
public static final Factory<Monster1> getFactory() {
return new Factory<Monster1>() {
public Monster1 make() { return new Monster1() ; }
};
}
}
public static class Monster2 extends BasicMonster {
public static final Factory<Monster2> getFactory() {
return new Factory<Monster2>() {
public Monster2 make() { return new Monster2() ; }
};
}
}
List<Factory<? extends BasicMonster>> monsterFactories= new ArrayList<Factory<? extends BasicMonster>>();
{
monsterFactories.add(Monster1.getFactory());
monsterFactories.add(Monster2.getFactory());
}
...
BasicMonster newMonster= monsterFactories.get(aRandomOne).make() ;
Form static class used to indicate classes not intended as inner.
Even if list monsterFactories were initialized through reflection, the presence of factory objects in the code permits a higher level of static analysis than reflective constructor invocation.
You could put all the classes in a specific package, then scan that directory for class files, load them, and track the ones that extend Monster. You could even define some custom annotations to help manage this, e.g. #IgnoreMonster to temporarily disable some without having to change the location of the file. This is similar to the way e.g. Hibernate scans source to find entity mappings.
Here is an example. All the Monster classes are placed in package dload.monsters. First, here's the base class I'm using for this example:
package dload.monsters;
public abstract class Monster {
public abstract String getName ();
}
Then, a MonsterFactory which scans for all classes in the dload.monsters package (sorry its a little sloppy, and I skimped out on exception handling):
package dload.monsters;
import java.io.*;
import java.net.*;
import java.util.*;
public class MonsterFactory {
private static final List<Class<? extends Monster>> monsterClasses = new ArrayList<Class<? extends Monster>>();
private static final Random random = new Random();
#SuppressWarnings("unchecked") // <- for monsterClasses.add((Class<? extends Monster>)cls);
public static void loadMonsters () throws Exception {
// in this example, Monster is in the same package as the monsters. if
// that is not the case, replace "." with path relative to Monster.
File folder = new File(Monster.class.getResource(".").toURI());
for (File f : folder.listFiles()) {
if (f.getName().endsWith(".class")) {
String name = f.getName().split("\\.")[0];
// replace "dload.monsters." below with package monsters are in
Class<?> cls = ClassLoader.getSystemClassLoader().loadClass("dload.monsters." + name);
// if Monster is not in same package as monsters, you can remove
// cls.equals(Monster.class) check. this check makes sure the loaded
// class extends Monster, but is not the Monster class itself (since
// its also in that package).
if (Monster.class.isAssignableFrom(cls) && !cls.equals(Monster.class)) {
System.out.println("Found " + cls.getSimpleName());
monsterClasses.add((Class<? extends Monster>)cls);
}
}
}
// at this point all Class's for monsters are in monsterClasses list.
}
public static Monster randomMonster () throws Exception {
// choose a class at random
int n = random.nextInt(monsterClasses.size());
Class<? extends Monster> cls = monsterClasses.get(n);
// instantiate it
return cls.newInstance();
}
}
Then, when you want to use it:
public static void main (String[] args) throws Exception {
// load monsters; only need to do this once at startup
MonsterFactory.loadMonsters();
// create 10 random monsters
for (int n = 0; n < 10; ++ n) {
Monster m = MonsterFactory.randomMonster();
System.out.println("name is " + m.getName());
}
}
Note that at any time you can check the monster's Class for relevant annotations.
Another option, if the classes are already loaded (which they won't be if they've never been used or explicitly loaded) is to use Instrumentation.getAllLoadedClasses() to get a list of all classes currently loaded, then scan through all classes looking for ones that are assignable to a Monster.
Note: I do feel like there is a cleaner way to do the actual scan, and I haven't tested this in a JAR. Suggestions welcome.
All that being said, if a Monster's behavior could be entirely defined by data, I also support and recommend the data driven approach described above.
You should take a look at the Cartesian Product Algorithm. It will generate every combination of products and you can then choose one at random.
Essentially the algorithm will take arrays of attributes and create unique combinations of the different attributes and add them to an array. You can then randomly select a key from the array when you create the enemy. That way every enemy has a random chance to have any number of attributes.
have an interface or base class that provides a monster.
I thought I'd include this wiki-bit, "The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created."
This lets you use superclass methods or interfaces exclusively without ever needing to know the specific subtype of the interface. This is important because you cannot call new base_monster();
abstract class base_monster {
abstract base_monster factory();
}
/// make sure every monster has a name...
//
abstract class Monster extends base_monster {
String name;
static int object_counter = 0;
Monster factory() {
name = Integer(object_counter).toString();
object_counter();
return this;
}
/// this class has a useful setter
void object_counter( int c ) { object_counter++; out.println( object_counter ); }
}
class Griffon extends Monster {
Monster factory() { return new Griffon(); }
}
class Harpy extends Monster {
Harpy() { name = "Grizelda WhuttleThut III"; }
Harpy factory() { return new Harpy(); }
}
class BlackHarpy extends Harpy {
BlackHarpy factory() { super.factory(); return new BlackHarpy(); }
}
// we assume that each class has a default constructor. But,
// if the array is filled with monsters of different subclasses we
// would have to use reflection or nasty instanceof switches to be
// able to call a (specific) defined constructor.
ArrayList<Monster> monsters = new ArrayList<Monster>();
monsters.add( new BlackHarpy() );
for( int I = 0; I < ave_monsters_appearing; I++ )
monsters.add( new Harpy() );
//
// an array of ten harpies and a boss Harpy.
///
// how can this array of monsters be copied into the other array?
// (we want object copies, not reference copies)
///
ArrayList<Monster> local_monsters = new ArrayList<Monster>();
/// solution: use the factory method
for( Monster m : monsters )
local_monsters.add( m.factory() );
.
.
Hope this solves the problem of not having a static method.

How do I extend a java class that is instantiated by another class?

Given two java classes, A and B, where A is usually instantiated via B, such as:
A myA = B.createA();
Can I create a subclass of A (let's call it SubA) and somehow have it be instantiated by the B.createA() method?
(Note that I cannot modify A and B....)
I know that not all instances of A are instances of SubA, thus I cannot do this:
SubA mySubA = B.createA();
Similarly, I cannot cast it like this either:
SubA mySubA = (SubA) (B.createA());
for the same reason -- it will get a ClassCastException.
Am I being dense and forgetting something fundamental, or is there no way to do this?
(Late addition: I'm so sorry, I should have mentioned that A and B have roughly 50 methods each, and all I want to do is add a single property to SubA, along with a getter and a setter. I'd really rather not implement all 50 of A's methods to invoke the corresponding method in the superclass's object.)
It sounds like like what you'd really like is to modify the behavior of both the original A and B. In that case, you could try extending both classes (where the extension of B is purely to specify a slightly different factory method for creating SubAs).
class SubA extends A {
/** This is the one special aspect of SubA justifying a sub-class.
Using double purely as an example. */
private double specialProperty;
public double getSpecialProperty() { return specialProperty; }
public void setSpecialProperty(double newSP) { specialProperty = newSP; }
public SubA() {
super();
// Important differences between SubAs and As go here....
// If there aren't any others, you don't need this constructor.
}
// NOTE: you don't have to do anything else with the other methods of
// A. You just inherit those.
}
class SubB extends B {
// Purely for the purposes of a slightly different factory method
public A createA() {
return new SubA();
}
// Or if you need a static method
// (this is usually instead of the first choice)
public static A createA() {
return new SubA();
}
}
Note that at this point, you could create one of your SubB factory objects and make it look like the original B like so:
B myNewB = new SubB();
A myA = myNewB.createA();
Or, if you're using the static factory instead, it isn't quite as close a match (but it's close).
A myA = SubB.createA();
Now, if you really need to do something with the sub-property, you'll have access to it via the child interface. I.e., if you create the object like so:
SubA mySubA = SubB.createA();
mySubA.setSpecialProperty(3.14);
double special = mySubA.getSpecialProperty();
Edit to discuss "Late addition":
At this point, your SubA object should be exactly what you want. It will inherit the 50 methods from the parent (A) and you can add your additional property to the child, plus the getter and setter. I changed the code above to illustrate what I mean.
This is usually done via a proxy:
class SubA extends A {
private A proxiedClass;
public SubA(A a) {
proxiedClass = a;
}
public int anyMethodInA() {
return proxiedClass.anyMethodInA();
}
}
...
SubA mySubA = new SubA(B.createA());
Doing this manually is rather verbose, so most people use some kind of a AOP library (like AspectJ) to only intercept method calls they are interested in.
You could create a wrapper around it, with SubA having a constructor that takes A as the parameter.
Like this:
SubA mySubA = new SubA(B.createA());
Since all instances of SubA are instances of A, you could then assign it to your existing A variable and override any necessary methods.
A myA = new SubA(B.createA());
I can't think of any other clean way of doing it.
If you are just wanting to add a field to A without object oriented such as changing behaviour, you could add it as an "external field". Use a WeakHashMap to map from instance of A onto the field value (just so long as the field value doesn't directly or indirectly reference A or you'll have an object life time contention issue):
private static final Map<A,FieldType> map =
new java.util.WeakHashMap<A,FieldType>(); // thread-safe from 1.6, IIRC
public static FieldType getField(A a) {
return map.get(a);
}
public static void setField(A a, FieldType value) {
map.set(a, value);
}
Really we should be using WeakIdentityHashMap, but it doesn't exist in the Java library!

Categories