协助关联方法调用

时间:2014-02-16 20:25:49

标签: c#

下面我有这个代码,我一直在努力进行练习,而不是分配工作,它是为了整合协会。在主要我有C2.buyPhoneApple(P1);这会在我的Customer类中调用该方法。回到我的主要,我有一个列表,这个列表是由添加到手机类的项目组成的,我的问题是,我用P1来测试通话,它有效,但现在我需要方法调用来反映内的项目列表,并在下订单后从库存中取1。我试图尽可能地解释这一点。

除此之外,我使用一个名为model的变量来存储迭代列表中的用户选择(0,1,2)我使用该变量通过索引applePhones库来确认用户选择,请原谅冗长的解释。

P.S。我确实有更多代码,但不觉得需要发布所有类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOP_Phone_Shop_Test
{
    class Program
    {

        static int thanksApple(ref int thankYou)
        {
            Random text = new Random();
            thankYou = text.Next(1, 4);

            switch (thankYou)
            {
                case 1:
                    Console.WriteLine("\nThank you for choosing Apple!\n");
                    break;
                case 2:
                    Console.WriteLine("\nCongratualation on purchasing your Apple product!\n");
                    break;
                case 3:
                    Console.WriteLine("\nWelcome to Apple, you shall receieve your account information and billing through the mail.\n");
                    break;
                case 4:
                    Console.WriteLine("\nCell-Sale, number 1 for Apple products and services!\n");
                    break;
            }

            return thankYou;
        }
        static void menu()
        {


        }
        static void Main(string[] args)
        {
            menu();
            int model = 0;
            bool menuRepeat = true;
            string confirm = "";
            int choice = 0;

            do
            {
                AppleLibrary appleLib = new AppleLibrary();
                SamsungLibrary samsungLib = new SamsungLibrary();
                Customer C1 = new Customer("Poseidon", 500, 309487, "The Sea, Greece"); //Instantiation with predefined values due to predefined constructor.
                Customer C2 = new Customer("Zeus", 601, 345928, "Olympus, Greece");
                Windows W1 = new Windows(); 



                W1.brand = "Windows"; 
                W1.model = "Nokia Lumia";
                W1.stock = 5;

                Samsung Sam2 = new Samsung(); 
                Sam2.brand = "Samsung, Andriod";
                Sam2.Model = "Samsung Galaxy note 3";
                Sam2.stock = 5;
                Sam2.price = 300;

                Apple P1 = new Apple();
                P1.brand = "Apple";
                P1.model = "iPhone 5";
                P1.stock = 5;
                P1.price = 350;

                appleLib.ApplePhones.Add(new Phone("Apple", "iPhone 5", 350, 1));//Adding to the library object with initialization (Predefined constructor)
                appleLib.ApplePhones.Add(new Phone("Apple", "iPhone 4s", 250, 1));
                appleLib.ApplePhones.Add(new Phone("Apple", "iPhone 3", 150, 0));
                samsungLib.samsungPhones.Add(new Phone("Samsung", "Galaxy Note 1", 100, 7));
                samsungLib.samsungPhones.Add(new Phone("Samsung", "Galaxy Note 2", 150, 2));
                samsungLib.samsungPhones.Add(new Phone("Samsung", "Galaxy Note 3", 350, 4));

                Console.BackgroundColor = ConsoleColor.DarkGreen;
                /*
                for (int j = 0; j < windowsPhoneArray.Length; j++)
                {
                    Console.WriteLine("{0}", windowsPhoneArray[j].model);
                }
                 * */

                Console.WriteLine("\nCustomer name: {0}\nCustomer balance: {1}\n", C1.name, C1.balance);

                Console.WriteLine("\n1)Apple\n\n2)Samsung\n\n3)Windows\n");

                Console.Write("Please select a brand: ");

                try
                {
                    choice = Convert.ToInt32(Console.ReadLine());
                }

                catch (FormatException)
                {
                    Console.BackgroundColor = ConsoleColor.DarkGray;
                    Console.WriteLine("\n\n***Please enter a number***\n\n");
                }

                if (choice == 1)
                {
                    Console.WriteLine("\nPlease Select a model");

                    for (int i = 0; i < appleLib.ApplePhones.Count(); i++)
                    {
                        Console.BackgroundColor = ConsoleColor.DarkMagenta;
                        Console.Write("\nSelection {0}) = Model: {1}\nPrice: {2}\nStock: {3}\n", i, appleLib.ApplePhones[i].model, appleLib.ApplePhones[i].price, appleLib.ApplePhones[i].stock);
                    }

                    Console.Write("\nPlease select your model: ");

                    try
                    {
                       model = Convert.ToInt32(Console.ReadLine()); //This variable to show/confirm the users list<phone> selection.
                    }

                    catch (FormatException)
                    {
                        Console.BackgroundColor = ConsoleColor.DarkGray;
                        Console.WriteLine("\nPlease enter a number\n");
                    }

                    Console.WriteLine("\nYou have selected: {0}\nPrice: {1}", appleLib.ApplePhones[model].Brand, appleLib.ApplePhones[model].price);


                    Console.BackgroundColor = ConsoleColor.Blue;
                    Console.Write("\nConfirm purchase Y/N: ");
                    confirm = Console.ReadLine();

                    if (confirm == "y" || confirm == "Y")
                    {
                        menuRepeat = false;
                        C2.BuyPhoneApple(P1);// I want this call to reflect the chosen element within the list<phone> and call buyPhoneApple and remove a phone from the stock according to the users selection.
                    }
                    else
                    {
                        Console.WriteLine("Returning to the main menu...standby");
                    }

                }

                if (choice == 2)
                {
                    for (int x = 0; x < samsungLib.samsungPhones.Count(); x++)
                    {
                        Console.Write("\nSelection {0}) = Model: {1}\nStock: {2}\n", x, samsungLib.samsungPhones[x].model, samsungLib.samsungPhones[x].stock);
                    }

                    Console.Write("\nPlease select your model: ");

                    try
                    {
                        model = Convert.ToInt32(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.BackgroundColor = ConsoleColor.DarkGray;
                        Console.WriteLine("\nPlease enter a number\n");
                    }

                    Console.WriteLine("\nYou have selected: {0}\nPrice: {1}", samsungLib.samsungPhones[model].brand, samsungLib.samsungPhones[model].price);

                    Console.Write("\nConfirm purchase Y/N: ");
                    confirm = Console.ReadLine();

                    if (confirm == "y" || confirm == "Y")
                    {
                        menuRepeat = false;
                        C2.BuyPhoneApple(P1);
                    }
                }
            } while (menuRepeat == true);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOP_Phone_Shop_Test
{
    class Apple : Phone
    {
        public Apple(string newBrand, string newModel, int newPrice, int newStock)
            : base(newBrand, newModel, newPrice, newStock)
        {
        }
        public Apple()
        {
        }
        static int thanksApple(ref int thankYou)
        {
            Random text = new Random();
            thankYou = text.Next(1, 4);

            switch (thankYou)
            {
                case 1:
                    Console.WriteLine("\nThank you for choosing Apple!\n");
                    break;
                case 2:
                    Console.WriteLine("\nCongratualation on purchasing your Apple product!\n");
                    break;
                case 3:
                    Console.WriteLine("\nWelcome to Apple, you shall receieve your account information and billing through the mail.\n");
                    break;
                case 4:
                    Console.WriteLine("\nCell-Sale, number 1 for Apple products and services!\n");
                    break;
            }

            return thankYou;
        }
        public override void OrderPhoneApple(Customer objCustomer)
        {
            int thankyouApple = 0;
            stock--;
            Console.WriteLine("\n\nSold!\n\nName: {0}\nAccount Number: {1}\nAddress: {2}", objCustomer.name, objCustomer.AccountNumber, objCustomer.Address);
            thanksApple(ref thankyouApple);
        }
        public override void AddStock()
        {
            stock++;
            Console.WriteLine("Single stock added!");
        }
        public override void AddMassStock(int MassStock)
        {
            stock = stock + MassStock;
            Console.WriteLine("stock added!");
        }
        public override void RemoveStock()
        {
            stock--;
            Console.WriteLine("Single stock removed!");
        }
        public override void RemoveMassStock(int RemoveMassStock)
        {
            stock = stock - RemoveMassStock;
            Console.WriteLine("stock removed!");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOP_Phone_Shop_Test
{
    class Customer
    {
        public string name;
        public double balance;
        public double accountNumber;
        public string address;

        public Customer(string newName, double newBalance, double newAccountNumber, string newAddress)
        {
            name = newName;
            balance = newBalance;
            accountNumber = newAccountNumber;
            address = newAddress;
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public double Balance
        {
            get
            {
                return balance;
            }
            set
            {
                balance = value;
            }
        }
        public double AccountNumber
        {
            get
            {
                return accountNumber;
            }
            set
            {
                accountNumber = value;
            }
        }
        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
            }
        }
        public void BuyPhoneApple(Apple objApplePhone)
        {
            if (balance >= objApplePhone.price)
            {
                objApplePhone.OrderPhoneApple(this);
            }
            else
            {
                Console.WriteLine("Not enouogh funds");
            }
        }
        public void BuyPhoneSamsung(Samsung objSamsungPhone)
        {
            if (balance >= objSamsungPhone.price)
            {
                objSamsungPhone.OrderPhoneSamsung(this);
            }
            else
            {
                Console.WriteLine("Not enough funds");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据您的问题和您发布的代码,您要问的是,您需要一种方法从苹果商店中删除已订购的手机,因为您是AppleLibrary类,并在处理链中使用购买的手机。

您需要做的第一件事是重构您的代码并使用服务方法来执行您在Phone模型类中填充的与订单相关的服务。

其次简化您的继承链,只使用枚举值属性指示手机类型。

然后通过删除所有Buy ***方法然后实现一个通用的Buy方法来简化客户域方法,该方法接收电话对象并将自己的电话对象或模型传递给您之前创建的PhoneOrderService。这可以用代码表示,如下所示

public class Customer
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public double AccountNumber { get; set; }
        public double AvaliableBalance { get; set; }

        public void Buy(Phone phone)
        {
            if (phone == null)
                return;
            var phoneService = new PhoneOrderService();

            if (phoneService.PurchasePhone(this, phone.Model))
            {
                Console.WriteLine("{0} phone purchased!", phone.Model);
            }
        }

namespace PhoneApp
{
    public enum PhoneType : int
    {
        Apple,
        Windows, 
        Samsung
    }


    public class Phone
    {
        public string Brand { get;  set; }
       public string Model { get;  set; }
       public double Price { get; set; }
       public int QuantityInStock { get; set; }
       public PhoneType PhoneType { get; set; }

    }
}

namespace PhoneApp
{
    public class PhoneOrderService
    {
        // I used a private static list here as a backup storeage for ease of 
        // implementation and simplicity of the example.
        private static List<Phone> _itemsInStock  = new List<Phone>();

        public void AddToStock(Phone phone)
        {
            if(phone == null)
                return;

            _itemsInStock.Add(phone);
        }

        //Now add those methods in your apple model to this service.

        public bool PurchasePhone(Customer customer, string model)
        {
            if (customer == null)
                return false;

            if (string.IsNullOrWhiteSpace(model))
                return false;

            var phone = _itemsInStock.FirstOrDefault(a => a.Model == model);


            if (phone != null)
            {
                if (customer.AvaliableBalance < phone.Price)
                    return false;

                customer.AvaliableBalance -= phone.Price;

                phone.QuantityInStock -= 1;    

                AddToStock(phone);
            }

            // then you use the phone to do whatever you like
            //after return true to the calling method to show that this action ucceeded.

            return true;
        }
    }
}


namespace PhoneApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //initialize the PhoneOrderService
            var phoneOrderService = new PhoneOrderService();

            //initialize the phone model
            var phone1 = new Phone
            {
                Model = "IPhone 5",
                Price = 450,
                QuantityInStock = 5,
                Brand = "Brand new",
                PhoneType = PhoneType.Apple
            };

            //initialize the phone model
            var phone2 = new Phone
            {
                Model = "Nokia Lumia",
                Price = 500,
                QuantityInStock = 3,
                Brand = "Brand new",
                PhoneType = PhoneType.Windows
            };

            //initialize the phone model
            var phone3 = new Phone
            {
                Model = "Galaxy 4 tab",
                Price = 350,
                QuantityInStock = 7,
                Brand = "Brand new",
                PhoneType = PhoneType.Samsung
            };

            //Add the phones to the phone order service
            phoneOrderService.AddToStock(phone1);
            phoneOrderService.AddToStock(phone2);
            phoneOrderService.AddToStock(phone3);


            //Initialize the customer model
            var customer = new Customer
            {
                Name = "Mr Moon",
                AvaliableBalance = 1000,
                Address = "41 new street road!",
                AccountNumber = 1234567889
            };

            customer.Buy(phone1);

            Console.ReadLine();
        }
    }
}