简体   繁体   中英

How to keep track of instances of another class in a class?

I have created a Sales class that keeps track of the name of the product, when it was sold and the price. I have a class called Client. How can I keep track of instances of the class Client in sales?

 class Sales
  {
    string productname;
    double price;
    private DateTime _salesDate;

    public Sales(string productname, double price)
    {
        this.productname = productname;
        this.price = price;
        _salesDate = DateTime.Now;
    }

Seems to me like the easiest way to do what you want is to add a property to the Sales class of type Client:

class Sales
{
    string productname;
    double price;
    private DateTime _salesDate;

    public Sales(string productname, double price, Client soldTo)
    {
        this.productname = productname;
        this.price = price;
        this.SoldTo = soldTo;
        _salesDate = DateTime.Now;
    }

    public Client SoldTo {get; private set;} // Added public to the property
}

If a single Sale can be to multiple clients, use a List<Client> instead of a single Client both in the constructor and as the property type.

List<Client> _soldToClients属性添加到您的销售类别

Here you go:

class Sales
{
    string productname;
    double price;
    private DateTime _salesDate;
    private List<Client> _SoldTheItemTo;

    public Sales(string productname, double price)
    {
        this.productname = productname;
        this.price = price;
        _salesDate = DateTime.Now;

        Client C = new Client();
        C.Name = "XYZ";
        _SoldTheItemTo.Add(C);
    }
}

Create class for product and it's related properties.

public class Product
{
     double price;
     string productname;

     public Product(string productname, double price)
     {
        this.productname = productname;
        this.price = price;
     }
}

And Your Sale Class,

public class Sale
{
     List<Product> Products;
     Client _SoldTheItemTo;

     public Sale(List<Product> products, Client client)
     {
        _SoldTheItemTo = client;
        Products = products;
     }
}

Try to keep separate each objects, as you know sales have multiple products and you will create separate invoice for each customer so no need to keep clients list, keep list of products and manage it according to your need.

If you want to develop this in the proper mannner with loose coupling then you should implement this in the " Observer Design Pattern ". The Observer defines a one-to-many relationship so that when one object changes state, the others are notified and updated automatically. Go through below links, study properly and then implement your problem:

Observer Design Pattern Reference 1

Observer Design Pattern Reference 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM