For creating singleton, usually we use the following static factory method where synchronized lock is on the class itself:
private volatile static MyClass instance;
public static MyClass getInstance() throws Exception {
if(instance == null) {
synchronized (MyClass.class) {
if(instance == null) {
instance = new MyClass();
}
}
}
return instance;
}
Instead, if we use a factory pattern and put the intrinsic lock on the factory class like:
public class MyFactory {
private volatile static MyClass instance = null;
public static MyClass getInstance() throws Exception{
if(instance == null) {
synchronized (MyFactory.class) {
if(instance == null) {
instance = new MyClass();
}
}
}
return instance;
}
}
---Here the factory pattern code has been simplified to showcase the lock rather than the logic of the pattern.
What will be the difference between putting the lock on the class instance itself Vs on the factory class that creates the instance?
When the instance is null and multiple threads race to get lock on the factory class Vs the class instance itself.....will there be any difference/error in the results for getting a singleton?
If you want to know more about singletons, I recommend that you read this article. It will give you a good explanation with nice snippets explaining the various implementations.
Related
As you know each anonymous object in java contains hidden reference to enclosing class.
But with kotling things get more complicated.
Lambda is another representation of anonymous class, but in kotlin it compiles not straightforward, because if lambda didn't capture a reference of enclosing class explicitely than it would be compiled like nested, not inner class (anonymous class) and is safe from the leak.
But what about inline functions. Consider the code below
class A {
fun test(){
val it = withReference {
//todo make sth
}
}
}
inline fun withReference(crossinline action: () -> Unit) = object: Reference {
override fun method1() {
action()
}
override fun method2() {
}
}
interface Reference {
fun method1()
fun method2()
}
As i know inline function would be compiled like non-wrapped code to the A class, so the question is open.
Does the anonymous object: Reference contain a link to enclosing class A, which could lead to a memory leak?
PS: i have read this article, but it doesn't contain an answer to my case
I used the decompiler of IntelliJ and there is no reference to the outer A
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
}
public void method2() {
}
}
If the lambda references a variable from the outer class A like this:
class A {
val valFromA = 10;
fun test(){
val it = withReference {
println("use $valFromA")
}
}
}
Then the decompiler shows the reference to the A object:
public final class A$test$$inlined$withReference$1 implements Reference {
// $FF: synthetic field
final A this$0;
public A$test$$inlined$withReference$1(A var1) {
this.this$0 = var1;
}
public void method1() {
String var1 = "use " + this.this$0.getValFromA();
System.out.println(var1);
}
public void method2() {
}
}
If you think about it, the withReference function has no way of referring to the outer scope that it gets inlined into, therefore it has no reason to contain a reference to the scope that it's called from. You don't even know what class it's being called in, or if it's even called inside a class, for that matter.
For this specific case, here's the decompiled and simplified bytecode of the withReference function:
public static Reference withReference(final Function0 action) {
return new Reference() {
public void method1() {
action.invoke();
}
public void method2() {
}
};
}
At the places where it gets inlined, there's of course no call to this function, this one is for Java interop only. Kotlin call sites all get their own class generated to represent this object depending on what code you pass into the action parameter. For your call of the test function, a class like is generated:
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
//todo make sth
}
public void method2() {
}
}
And this is what's instantiated in the test method:
public final class A {
public final void test() {
Reference it = new A$test$$inlined$withReference$1();
}
}
I am a Java programmer trying to learn groovy. Closures are a bit confusing for me at the moment.
Could I have some help to understand how I can use a closure to replace the abstract code I have below. I'm thinking a function defined as a variable or something like that however I can't crack it yet.
//MY ABSTRACT CLASS
public abstract class AbstractResource {
protected StreamingOutput activityStreamingOutput(serviceResponse){
return new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
def writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write(serviceResponse);
writer.flush();
}
}
}
}
// MY CHILD CLASS
class MaintanenceResourceImpl extends AbstractResource{
public void doSomething(Reader reader) throws Exception {
// I'D LIKE TO DO SOMETHING GROOVYISH HERE
def StreamingOutput = activityStreamingOutput(serviceResponse)
}
thanks
There's not much you can do here (w/o knowing other details), but this:
abstract class AbstractResource {
Closure activityStreamingOutput(serviceResponse){
{ OutputStream os ->
os.withWriter{ it << serviceResponse }
}
}
}
class MaintanenceResourceImpl extends AbstractResource {
void doSomething(Reader reader) throws Exception {
activityStreamingOutput(serviceResponse).call someOutputStream
}
I have created the class name cls1 and created method called GrantAccess().but the i am not able to access _entities.it's showing the below error
"Error 1 An object reference is required for the non-static field, method, or property 'Path._entities".
public class cls1
{
private readonly DBEntities _entities;
public cls1 ()
{
if (_entities == null)
{
_entities = new DBEntities();
}
}
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
}
The above method is called in some other class.
public void GetCConfig()
{
cls1.GrantAccess();
}
GrantAccess is a static method while _entities is not a static variable. So you need to make GrantAccess a non-static method or you have to make _entities a static variable.
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
Or create a new instance of DBEntities in the static GrantAccess method and perform your operation on this instance.
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
DBEntities entities = new DBEntities();
entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
first you have to create an object of cls1 in the class where you are calling the method of the cls1 class and then with from that object reference you will be able to call the method GrantAccess();. You can create object by following way :-
variable_name = new class_name( );
You are mixing static code with instance code. If you're working with objects, don't make your method GrantAccess static:
public void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
Then you'll have to create an instance of cls1:
public void GetCConfig()
{
var instance = new cls1();
cls1.GrantAccess();
}
You should also make cls1 disposable and call .Dispose() on _entities after you're finishied using it.
public class cls1 : IDisposable
{
...
public void Dispose()
{
_entities.Dispose();
}
Put the cls1 instance into a using block, like this:
public void GetCConfig()
{
using(var instance = new cls1())
{
cls1.GrantAccess();
}
}
Finally, the following line is not needed, because _entities will always be null at the beginning of the constructor.
if (_entities == null)
{
I'd suggest reading some basic documentation about object oriented programming with c#, for example:
https://msdn.microsoft.com/en-us/library/dd460654.aspx
I am trying to learn IOC principle from this screencast
Inversion of Control from First Principles - Top Gear Style
I tried do as per screencast but i get an error while AutomaticFactory try create an object of AutoCue. AutoCue class has contructor which takes IClock and not SystemClock. But my question is , in screencast IClock is resolved with SystemClock while inside AutomaticFactory .But in my code , IClock does not get resolved . Am i missing something ?
class Program
{
static void Main(string[] args)
{
//var clarkson = new Clarkson(new AutoCue(new SystemClock()), new Megaphone());
//var clarkson = ClarksonFactory.SpawnOne();
var clarkson = (Clarkson)AutomaticFactory.GetOne(typeof(Clarkson));
clarkson.SaySomething();
Console.Read();
}
}
public class AutomaticFactory
{
public static object GetOne(Type type)
{
var constructor = type.GetConstructors().Single();
var parameters = constructor.GetParameters();
if (!parameters.Any()) return Activator.CreateInstance(type);
var args = new List<object>();
foreach(var parameter in parameters)
{
var arg = GetOne(parameter.ParameterType);
args.Add(arg);
}
var result = Activator.CreateInstance(type, args.ToArray());
return result;
}
}
public class Clarkson
{
private readonly AutoCue _autocue;
private readonly Megaphone _megaphone;
public Clarkson(AutoCue autocue,Megaphone megaphone)
{
_autocue = autocue;
_megaphone =megaphone;
}
public void SaySomething()
{
var message = _autocue.GetCue();
_megaphone.Shout(message);
}
}
public class Megaphone
{
public void Shout(string message)
{
Console.WriteLine(message);
}
}
public interface IClock
{
DateTime Now { get; }
}
public class SystemClock : IClock
{
public DateTime Now { get { return DateTime.Now; } }
}
public class AutoCue
{
private readonly IClock _clock;
public AutoCue(IClock clock)
{
_clock = clock;
}
public string GetCue()
{
DateTime now = _clock.Now;
if (now.DayOfWeek == DayOfWeek.Sunday)
{
return "Its a sunday!";
}
else
{
return "I have to work!";
}
}
}
What you basically implemented is a small IoC container that is able to auto-wire object graphs. But your implementation is only able to create object graphs of concrete objects. This makes your code violate the Dependency Inversion Principle.
What's missing from the implementation is some sort of Register method that tells your AutomaticFactory that when confronted with an abstraction, it should resolve the registered implementation. That could look as follows:
private static readonly Dictionary<Type, Type> registrations =
new Dictionary<Type, Type>();
public static void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class
{
registrations.Add(typeof(TService), typeof(TImplementation));
}
No you will have to do an adjustment to the GetOne method as well. You can add the following code at the start of the GetOne method:
if (registrations.ContainsKey(type))
{
type = registrations[type];
}
That will ensure that if the supplied type is registered in the AutomaticFactory as TService, the mapped TImplementation will be used and the factory will continue using this implementation as the type to build up.
This does mean however that you now have to explicitly register the mapping between IClock and SystemClock (which is a quite natural thing to do if you're working with an IoC container). You must make this mapping before the first instance is resolved from the AutomaticFactory. So you should add the following line to to the beginning of the Main method:
AutomaticFactory.Register<IClock, SystemClock>();
I'm looking to abstract a helper method. The method needs to be able to take in an object, do things with it depending on the type of object, and return a value. Would it be better to do something like this:
interface ICanDo
{
string DoSomething();
}
string DoThings(ICanDo mything)
{
return mything.DoSomething();
}
Or is it better to do something like this:
interface IStrategy
{
string DoSomething(object o);
}
string DoThings(object mything, IStrategy strategy)
{
return strategy.DoSomething(mything);
}
Is the latter even using a strategy pattern, since the strategy isn't being built into the class?
Is there a better way to do this I'm not thinking of? Would it be better to build the strategy into the class, using a wrapper for any class that needs to have DoThings run on it?
Sorry--I'm new to this pattern and trying to figure out where and how to use it best.
This is what I ended up putting together. I'm unsure if this follows good development principles.
class IndexWrapper
{
public interface IDocumentable
{
Document BuildDocument();
}
public interface IDocumentBuilder
{
Type SupportedType { get; }
Document BuildDocument(object o);
}
public class StringDocumentBuilder : IDocumentBuilder
{
public Type SupportedType { get { return typeof(string); } }
public Document BuildDocument(object o)
{
Document doc = new Document();
doc.Add(new Field("string", o as string, Field.Store.YES, Field.Index.ANALYZED));
return doc;
}
}
public static class IndexableFactory
{
public static IDocumentable GetIndexableObject(object o)
{
return GetIndexableObject(o, DocumentBuilderFactory.GetBuilder(o));
}
public static IDocumentable GetIndexableObject(object o, IDocumentBuilder builder)
{
return new IndexableObject(o, builder);
}
}
public static class DocumentBuilderFactory
{
private static List<IDocumentBuilder> _builders = new List<IDocumentBuilder>();
public static IDocumentBuilder GetBuilder(object o)
{
if (_builders.Count == 0)
{
_builders = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => typeof(IDocumentBuilder).IsAssignableFrom(type) && type.IsClass)
.Select(type => Activator.CreateInstance(type))
.Cast<IDocumentBuilder>()
.ToList();
}
return _builders.Where(builder => builder.SupportedType.IsAssignableFrom(o.GetType())).FirstOrDefault();
}
}
private class IndexableObject : IDocumentable
{
object _o;
IDocumentBuilder _builder;
public IndexableObject(object o) : this(o, DocumentBuilderFactory.GetBuilder(o)) { }
public IndexableObject(object o, IDocumentBuilder builder)
{
_o = o;
_builder = builder;
}
virtual public Document BuildDocument()
{
return _builder.BuildDocument(_o);
}
}
}
When in doubt, keep the KISS mantra in your mind - Keep It Short and Simple. Patterns can be very useful, but often they're only useful in specific cases and add unnecessary complexity otherwise.
In my experience, the strategy pattern is useful for when you have multiple different backends to choose from for a class. For example, say you have a logging class that your program uses to print debug information. Maybe in some cases, you want to log to a file. Maybe you'd like to log to a console. Perhaps you'd even like to log to a remote server with a proprietary protocol you company made!
So, your logging class may look like this:
interface IOutputWriter
{
void WriteLn(string message);
}
class ConsoleWriter : IOutputWriter
{
public ConsoleWriter()
{
}
public void WriteLn(string message)
{
Console.WriteLine(message);
}
}
class NetworkWriter : IOutputWriter
{
public NetworkWriter()
{
}
public void WriteLn(string message)
{
//Crazy propietary server protocol action
}
}
class Logger
{
IOutputWriter writer;
public Logger(IOutputWriter writer)
{
this.writer = writer;
}
public void Log(string message)
{
writer.WriteLn(message + "Date");
}
}
With the end result that your program code looks like this:
class Program
{
static void Main(string[] args)
{
Logger logger = new Logger(new ConsoleWriter());
logger.Log("Test");
}
}
The benefit is that if you want to use your crazy networking protocol, you can do it without even looking at the logging class. You just have to make a new class with your IOutputWriter interface and tell your logger to use your custom backend. The strategy pattern is essentially defining reusable interfaces and then using those interfaces to decouple algorithms from each other.