Can a class return an object on its own

Can a class return an object on its own.

In my example, I have a class called "Change", which represents a change in the system, and I wonder if in any case, against the principles of design, it returns an object of type Change or ArrayList, which is filled with all the latest Change objects.

+5
source share
7 answers

Yes maybe. In fact, this is what a singleton class does. The first time a class method is called getInstance()at the class level, it creates an instance of itself and returns it. Subsequent calls then getInstance()return an already constructed instance.

, - . , . . , - ++ (), , .

, Java, , ​​ .

. , , , , . , (null, , ) , .

, , , .

, ( ). , .

, , .

+3

this , :

class foo
{
    private int x;
    public foo()
    {
        this.x = 0;
    }

    public foo Add(int a)
    {
        this.x += a;
        return this;
    }

    public foo Subtract(int a)
    {
        this.x -= a;
        return this;
    }

    public int Value
    {
        get { return this.x; }
    }

    public static void Main()
    {
        foo f = new foo();
        f.Add(10).Add(20).Subtract(1);
        System.Console.WriteLine(f.Value);
    }
}
$ ./foo.exe
29

, " ". LINQ , .

+5

, "factory". Java ++ ( ..) , . , .

Java :

List<Change> changes = Change.getRecentChanges();

, Change , , , - .

, , :

Foo foo = Foo.getInstance();
+3

, , . .

# :

public class Change
{
    public int ChangeID { get; set; }

    private Change(int changeId)
    {
        ChangeID = changeId;
        LoadFromDatabase();
    }

    private void LoadFromDatabase()
    {
        // TODO Perform Database load here.
    }

    public static Change GetChange(int changeId)
    {
        return new Change(changeId);
    }
}
+3

, .

StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
+1

, . ChangeList, Change.

, , , , , . . node, .

Another common scenario is to implement a class with a static method that returns an instance of it. This should be used when creating a new instance of the class.

+1
source

I don’t know a single design rule that says it’s bad. Therefore, if in your model one change can consist of several changes, go to it.

0
source

All Articles