Scala Singleton对象用于扩展类和传递参数

时间:2018-01-23 07:38:56

标签: scala

我在Scala中为具有参数的类创建单例并且正在扩展抽象类时遇到问题。我需要在类中编写所有逻辑,因为我不应该错过抽象类的任何功能,并且必须通过使用Scala private void getAddressFromLocation(double latitude, double longitude) { Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses.size() > 0) { Address fetchedAddress = addresses.get(0); StringBuilder strAddress = new StringBuilder(); for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) { strAddress.append(fetchedAddress.getAddressLine(i)).append(" "); } txtLocationAddress.setText(strAddress.toString()); } else { txtLocationAddress.setText("Searching Current Address"); } } catch (IOException e) { e.printStackTrace(); printToast("Could not get address..!"); } } 将其限制为只访问一种方式。

object以下需要创建为单身。

GenerateCountryAnimal

2 个答案:

答案 0 :(得分:2)

在Scala中,单身人士通常由object代表。在您的情况下,您仍然可以通过将原始abstract class扩展为另一个实现逻辑的object来使用它,然后根据您的需要使用不同的abstract class Animal { def giveAnimalData(): DataFrame } abstract class GenerateCountryAnimal(tableA: Table, tableB: Table) extends Animal { // implement giveAnimalData method } object YourSingleton extends GenerateCountryAnimal(??? : Table, ??? : Table)

object

如果您需要在运行时获取这些参数,您可能希望利用// The object will be created only when first referred to and you can use // this characteristic to set the value of tableA and tableB to those that // are relevant for you object GenerateCountryAnimal extends Animal { val tableA: Table = ??? val tableB: Table = ??? def giveAnimalData(): DataFrame = ??? } s是懒惰创建的事实:

{{1}}

否则,您可能只想将单例模式移植到Scala,这在this post中有详尽描述。

答案 1 :(得分:1)

A&#34;单身参数&#34;没有多大意义。 Singleton表示整个系统中有一个类的实例。如果是这种情况,则不需要任何参数。

我假设您并不真正需要单个实例,而是每个参数组合需要一个实例。这被称为&#34;规范化&#34;。我们的想法是你制作一个地图,你可以保存你的规范实例,以及一个管理它的工厂方法:

   object Animal {

        import java.util.function.Function
        import java.util.concurrent.ConcurrentHashMap

        private class GenerateCountryAnimal(tableA: Table, tableB: Table) extends Animal {
           // your implementation here
        }
        object Factory extends Function[(Table, Table), Animal] {
          def apply(key: (Table, Table)) = new GenerateCountryAnimal(key._1, key._2) 
        }
        val canon = new ConcurrentHashMap[(Table,Table), Animal]()
        def apply(a: Table, b: Table) = canon
           .computeIfAbsent((a,b), Factory)
   }

这样,您可以执行val animal = Animal(foo, bar),并且它将始终为同一对参数返回相同的实例。 (我假设您的Table具有hasCodeequals正常工作,因此可以将其用作哈希映射中的键。

要明确,我非常怀疑你在做什么实际上是一个好主意。 虽然可以例外,但通常不需要在scala中规范化这样的实例。除非你有一些特定的晦涩理由,否则你应该将GenerateCountryAnimal作为案例类,并根据需要使用GenerateCountryAnimal(a,b)进行实例化。

如果其中有任何特定资源,您希望成为单身人士,那么将 作为单身人士(另一个答案描述的方式)。

相关问题