Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- using System.Threading.Tasks;
- namespace Prototype
- {
- static class ExtensionMethods
- {
- public static T DeepCopy<T>(this T self)
- {
- if (!typeof(T).IsSerializable)
- throw new ArgumentException("type must be serializable");
- if (ReferenceEquals(self, null))
- return default(T);
- var formatter = new BinaryFormatter();
- using (var stream = new MemoryStream())
- {
- formatter.Serialize(stream, self);
- stream.Seek(0, SeekOrigin.Begin);
- return (T)formatter.Deserialize(stream);
- }
- }
- }
- class EmployeeFactory
- {
- private static Contact main = new Contact() { WorkAdress = new Address() { City = "London", Street = "221b Baket Sr", Suite = 100 } };
- private static Contact aux = new Contact() { WorkAdress = new Address() { City = "London", Street = "250", Suite = 100 } };
- private static Contact NewEmployee(string name, int suite, Contact prototype)
- {
- var result = prototype.DeepCopy();
- result.Name = name;
- result.WorkAdress.Suite = suite;
- return result;
- }
- public static Contact NewMainOfficeEmployee(string name, int suite)
- {
- return NewEmployee(name, suite, main);
- }
- public static Contact NewAuxOfficeEmployee(string name, int suite)
- {
- return NewEmployee(name, suite, aux);
- }
- }
- [Serializable]
- public class Contact
- {
- public string Name;
- public Address WorkAdress;
- public override string ToString()
- {
- return $"Name: {Name}, WorkAdress: {WorkAdress}";
- }
- }
- [Serializable]
- public class Address
- {
- public string Street;
- public string City;
- public int Suite;
- public override string ToString()
- {
- return $"Street: {Street}, City: {City}, Suite: {Suite}";
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- var john = EmployeeFactory.NewMainOfficeEmployee("John", 100);
- var jill = EmployeeFactory.NewAuxOfficeEmployee("Jill", 1000);
- Console.WriteLine(john);
- Console.WriteLine(jill);
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement