如何在不同的类型ArrayList中使用相同的方法?

时间:2016-08-17 03:35:55

标签: java class arraylist refactoring

我正在做一个应该存储在两个不同文本文件中的项目。假设我有2个Person和Activity类,每个类只有这些属性的共同点:id和isActive。但也有许多并不常见。

我也有2个类ArrayList类型:

import UIKit
var favoritePlaces = [String]()

class SecondViewController: UIViewController, UITableViewDelegate, UITextFieldDelegate, UITableViewDataSource {



    @IBAction func alertButtonPressed(sender: AnyObject) {


            let addNewPlaceAlert = UIAlertController(title: "Add A Favorite Place", message: "Enter the name of the place here", preferredStyle: .Alert)
        let saveAction = UIAlertAction(title: "Done", style: .Default) { (alert: UIAlertAction!) -> Void in
            NSLog("You pressed button OK")
            addNewPlaceAlert.dismissViewControllerAnimated(true, completion: nil)
            let textField = addNewPlaceAlert.textFields![0] as UITextField
            favoritePlaces.append(textField.text!)
            self.favoritePlacesTable.reloadData()
            NSUserDefaults.standardUserDefaults().setObject(favoritePlaces, forKey: "favoritePlaces")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (alert: UIAlertAction!) -> Void in
            NSLog("You pressed button OK")


        }

    addNewPlaceAlert.addAction(saveAction)
        addNewPlaceAlert.addAction(cancelAction)
        addNewPlaceAlert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in

                   }

        presentViewController(addNewPlaceAlert, animated: true, completion: nil)




    }
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            favoritePlaces.append(alertView.textFieldAtIndex(0)!.text!)
            favoritePlacesTable.reloadData()
        }
    }


    @IBOutlet var favoritePlacesTable: UITableView!

      override func viewDidLoad() {

        super.viewDidLoad()

        if NSUserDefaults.standardUserDefaults().objectForKey("favoritePlaces") != nil {

            favoritePlaces = NSUserDefaults.standardUserDefaults().objectForKey("favoritePlaces") as! [String]


        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        favoritePlacesTable.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        print("Row: \(row)")

        print(favoritePlaces[row] as String)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section:Int) -> Int {

        return favoritePlaces.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell? = favoritePlacesTable.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
        cell!.textLabel?.text = favoritePlaces[indexPath.row]

        if (cell != nil)
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
                                   reuseIdentifier: "Cell")
        }

        // At this point, we definitely have a cell -- either dequeued or newly created,
        // so let's force unwrap the optional into a UITableViewCell


        return cell!
    }
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let row = indexPath.row
        performSegueWithIdentifier("showContent", sender: row)
    }


    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {

            favoritePlaces.removeAtIndex(indexPath.row)

            NSUserDefaults.standardUserDefaults().setObject(favoritePlaces, forKey: "favoritePlaces")

            favoritePlacesTable.reloadData()
        }
    }







    override func viewDidAppear(animated: Bool) {

        favoritePlacesTable.reloadData()

            }



}

    Favorite Place View Controller(The view that opens once a user selects a row)
 import UIKit

class FavoritePlaceViewController: UIViewController {

    enter code here
    @IBOutlet var favoritePlaceWV: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

let url = NSURL(string: "https://www.google.com")!
        favoritePlaceWV.loadRequest(NSURLRequest(URL: url))
        // Do any additional setup after loading the view.

        NSUserDefaults.standardUserDefaults().objectForKey("secondUrl")
    }

    `enter code here`override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

public class RegistryPerson extends ArrayList<Person> {
     public void add(Person obj){
              ....
     }
     public boolean isDuplicate(Person obj){
         for(Person p: this){
             if(obj.equals(p)){ 
                 return true;
             }
         }
         return false;
     } 
     public Person search(int id){
              ....
     }
     public void readFile(){
         otherClass.readFile(String txtfilePerson);
     } 
     public void activate(Person obj){
              obj.setActivate;
     }
     //more methods
}

两个类都有相同的方法

如您所见,类型ArrayList RegitryPerson和RegistryActivigy具有相同的方法,但有些使用了不同类型的对象。

我只是不想在不同的类中使用几乎相同的代码。我可以使用接口或抽象类吗?而最重要的是,如何实现呢?或者我使一切变得复杂?

感谢。

2 个答案:

答案 0 :(得分:3)

您可以在此处遵循Program to an interface, not implementations设计原则。

创建一个由interfaceEntity

实施的PersonActivity

<强> Entity.java

public interface Entity {
    public Boolean equals(Entity e);
    //other common methods
}

此界面将由PersonActivity

实施

<强> Person.java

public class Person implements Entity {
    ...
    @Override
    public boolean equals(Entity e) {
        ...
    }
    ...
}

<强> Activity.java

public class Activity implements Entity {
    ...
    @Override
    public boolean equals(Entity e) {
        ...
    }
    ...
}

现在创建父类注册表

<强> Registry.java

public class Registry extends ArrayList<Entity> {
     public void add(Entity obj){
              ....
     }
     public boolean isDuplicate(Entity obj){
         for(Entity p: this){
             if(obj.equals(p)){ 
                 return true;
             }
         }
         return false;
     } 
     public Entity search(int id){
              ....
     }
     public void readFile(){
         otherClass.readFile(String txtfilePerson);
     } 
     public void activate(Entity obj){
              obj.setActivate;
     }
     //more methods
}

现在,您可以将此Registry类扩展到两个实现,即RegistryPersonRegistryActivity

<强> RegistryPerson.java

public class RegistryPerson extends Registry {
    ..
}

<强> RegistryActivity.java

public class RegistryActivity extends Registry {
    ..
}

P.S。:上面列出的所有类都包含更常用的方法。这只是为了让您基本了解这一设计原则。

答案 1 :(得分:2)

我有与rD相同的想法,但使用泛型来创建注册表。我还在课堂内移动了List。从文件读取和添加注册表的方法可以由其他类处理。我试图不惜一切代价避免继承和抽象类。接口是泛型非常强大。

interface IdObject {
    int getId();
}

class Registry<T extends IdObject> {
    private List<T> list = new ArrayList<T>();

    public void add(T obj){
        list.add(obj);
    }

    public boolean isDuplicate(T obj){
        for(T t: list){
            if(obj.equals(t)){
                return true;
            }
        }
        return false;
    }
    public T search(int id){
        for(T t: list){
            if(t.getId() == id)){
                return t;
            }
        }
        return null;
    }
}

class Example {
    Registery<Person> personRegistery = new Registry<>();
    Registery<Activity> activityRegistery = new Registry<>();
}