How Cloning Breaks singleton - singleton

1) Singleton means the class have one instance. Having private constructer. No way to create object except reflection. No subclassing.
If i want to clone my singleton classthen class must and should implement Cloneable and override clone() right.
am not going to implement Cloneable interface in my Singleton class.
Then how cloning breaks my singleton. is this correct. Please clarify some one. if am wrong.
what is the need of throwing clonenotsupported exception.

No reason to implement Cloneable and override clone() to throw CloneNotSupportedException. Object. Clone, throws expectation when the Cloneable interface is absent.
The correct way to create singleton class using enums can be referred in my favorite java book "Effective Java" . Please read that.

Related

Is there a solution to "Cannot access '<init>': it is private in XYZ?

I included a library I'd like to use, but in accessing to one of its classes I get the error message,
"Cannot access '<init>': it is private in [class name]
Is there something I can do to rectify this on my side, or am I just stuck to not use the package?
The error means the constructor is private. Given your comment, I'm assuming you're using a library. If this is the case, you'll have to find a different way to initialize it. Some libraries have factories or builders for classes, so look up any applicable documentation (if it is a library or framework). Others also use the singleton pattern, or other forms of initialization where you, the developer, don't use the constructor directly.
If, however, it is your code, remove private from the constructor(s). If it's internal and you're trying to access it outside the module, remove internal. Remember, the default accessibility is public. Alternatively, you can use the builder pattern, factory pattern, or anything similar yourself if you want to keep the constructor private or internal.
I came across this issue when trying to extend a sealed class in another file. Without seeing the library code it is hard to know if that is also what you are attempting to do.
The sealed classes have the following unique features:
A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
Classes that extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily in the same file.
For more info, have a read at https://www.ericdecanini.com/2019/10/14/kotlins-sealed-class-enums-on-steroids/
Hopefully, this will help others new to Kotlin who are also encountering this issue.
Class constructors are package-private by default. Just add the public keyword before declaring the constructor.
By default constructor is public so need to remove internal keyword.

When to use singletons in OOP?

When reading about singletons, I have found this explanation as a reason to use singleton:
since these object methods are not changing the internal class state, we
can create this class as a singleton.
What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?
Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?
I am using PHP, but may understand examples written in JAVA, C#...
This is the article reference. You can ctrl+f search for "internal". Basically, autor is explaining why FileStorage class is a good candidate to be a singleton. I do not understand this sentance
"These operations do not change the internal class state, so we can
create its instance once and use it multiple times."
and therefore I do not understand when to use singletons.
In their example, they have some FileStorage class :
class FileStorage
{
public function __contruct($root) {
// whatever
}
public function read() {
// whatever
}
public function write($content) {
// whatever
}
}
And they say that this class can be a singleton since its methods read() and write() do not chage internal class structure. What does that mean ? They are not setters and class is automatically singleton ?
The quote reads:
These operations do not change the internal class state, so we can create its instance once and use it multiple times.
This means that the object in question has no interesting internal state that could be changed; it’s just a collection of methods (that could probably be static). If the object has no internal state, you don’t have to create multiple instances of it, you can keep reusing a single one. Therefore you can configure the dependency injection container to treat the object as a singleton.
This is a performance optimization only. You could create a fresh instance of the class each time it’s needed. And it would be better – until the object creation becomes a measurable bottleneck.

"Abstract" methods in Yii Behaviors

I've been developing Yii application. And I'm wondering if it's possible to declare in model behavior some kind of "abstract" method. I know that it impossible to use directly following declaration:
abstract class FantasticBehavior extends CActiveRecordBehavior
{
public abstract function doSomethingFantastic();
}
because we need an instanse of this class. But also I know that Yii is full magic:)
I just want to make owner class to redeclare method from the behavior in obligatory order. Sure, I can use interface in addition to behavior but ...
Sorry if I've missed something to tell or something is not clear. Just ask and I'll try to explain what I mean.
Does anybody know something about this?
Thanks in advance.
UPD
I do understand that Yii is just PHP. It doesn't extend PHP. It is superstructure over it. And it doesn't have multiple inheritance since PHP doesn't.
I do understand behavior method can't be declared using abstract keyword. That is why I have written word "abstract" in quotes. But whatever. I know how behaviors work.
My question was if I can somehow oblige model(e.g. child of CActiveRecord) to declare some method.
For example, for my purposes I can do something like this:
class FantasticBehavior extends CActiveRecordBehavior
{
public function doFantasticThings()
{
$this->owner->prepareForFantastic();
// some code
}
}
Therefore, if I attach this behavior to my model and call method doFantasticThings this method will try to call method prepareForFantastic from model(owner). And if model doesn't have method prepareForFantastic declared new exception will be thrown because non-declared method are called.
Looks like I've answered my question myself :) What do you think about this?
UPD2
Yes, I know that if we don't call "abstract" method we won't know that it is not declared. It is a "charm" of interpretable languages :) We don't know if there is any error untill the code is run. Although, it would awesome if we could know about this as earlier as possible. For example, once instance of FantasticBehavior-class is attached to the model we could throw some child of CException to show what required methods must be declared in model. To achive this we can use something like listed below:
class FantasticBehavior extends CActiveRecordBehavior
{
public function attach($owner)
{
if(!/*$owner has declared methods list this->abstractMethods*/)
{
throw new CAbstractMethodNotDecalared('....');
}
parent::attach($owner);
}
public function abstractMethods()
{
return array('prepareForFantastic');
}
}
We need to override method attach from class CBehavior and check if "abstract" methods declared. Method abstractMethods is used to get list "abstract" method.
I don't know if there is attachBehavior event exists. If so, we can use it instead of overriding attach method.
Using this idea Base class for behaviors with "abstract" methods.
What do you think about this?
Maybe in future I'll make extention for Yii and become famous and rich? :))
This might be a little confusing to explain...
No, you cannot "attach" abstract methods to your CActiveRecord model using Yii's Behaviors. All Behavior's do is some clever overrides of __call(), __get() and __set() that give the illusion of multiple inheritance. (This is a good article about it). Behaviors do not provide true "multiple inheritance" support for core language features like abstract classes and interfaces. So if you attach that Behavior and add doSomethingFantastic() to your CActiveRecord class, you will still get an error.
You can, of course, declare abstract Behaviors that other Behaviors extend. So if you created another SuperFantasticBehavior Behavior that extended FantasticBehavior and implemented doSomethingFantastic() in it, you'll be fine. But it won't force you to declare the doSomethingFantastic() method in the CActiveRecord itself.
For a little deeper understanding: The way Yii's CComponent::_call() override is structured, when you call a method it will first see if any of the behaviors have that method, and call the method on the class itself.
Behavior's seem cool at first (mixins!), but sometimes it's just better to remember that PHP is a single class inheritance language and keep is simple. ;)
UPDATE:
The difference is that if you could use abstract methods in this case you'd see a "Class must implement method" error when you try to run your code (any code), and your IDE would highlight the error. This is more of a "compile" time error (not that it really exists in an interpreted lang like PHP).
Instead you'll see a "non-declared method" error (as you mention) at runtime. But you won't see it until that method is actually called, meaning you don't get that nice early warning like an abstract definition would give you. And if that method is never called, you won't get the error, which to means it's not really "obliging" the declaration in the same way an abstract def would.
Sorry if my initial answer was starting out at too basic of a level, I just wanted to be sure there was no misunderstanding. It's an interesting discussion, and made me think more about what an abstract declaration really does. Thanks, and happy coding! :)
Cheers

static function in class which instantiates object

I often use a pattern where I have a static member function in a class which instantiates object of itself, uses it, and destroys it.
Is this a good pattern? I think so. Does the pattern have a name?
I guess it's sort of a combination of Singleton and Factory method patterns. "Singletory" maybe?
The pattern is called 'Factory method'.
I often use this pattern, if using a factory class is a bit overkill, and when creating an instance of the class is a bit cumbersome (some initialization that has to be done for instance on other objects), or, when you want to have an easy way of creating different types of instances of that class.
are you saying you are doing this
class MyClass {
static void util(){
obj = new MyClass();
obj.InstanceMem();
obj.destroy();
}
void InstanceMem(){}
}
i see this more of a utility method.
well if you think it solves a common reoccurring problem then it may be called as a pattern.

metaclass & constructors

It is my understanding that it is difficult to create constructors of classes in Smalltalk and Objective-C. This is because the constructor can't be a message of a class instance because the class Class is not yet defined.
As far as I can tell, the solution is to create a new class whose only instance is itself a class. But how does the constructor work in this situation? I don't understand the process.
I'm talking in terms of Smalltalk. There are two types of things that you could reasonably call constructors here. One is the method that initializes a new instance of a class. The other is the things that initializes a class. Neither of them is difficult.
For instance initialization, the convention is that you implement the "new" method on the class as
new
^super new initialize
(do the superclass's implementation of new, and then send the "initialize" message to the result and return it)
Lots of classes may already inherit this implementation, so you just need to write an initialize method as
initialize
super initialize.
foo := 1.
etc.
To initialize a new class, the mechanism is similar. You implement a class method called "initialize", and it will automatically get sent when the class is loaded into a new Smalltalk environment (image).
The solution is to create a method on the class which does all the necessary initialisation of the instance.